]> de.git.xonotic.org Git - xonotic/netradiant.git/blob - radiant/texwindow.cpp
Merge commit 'ff48e71434a414958e6e56628ccf04284d030784' into master-merge
[xonotic/netradiant.git] / radiant / texwindow.cpp
1 /*
2    Copyright (C) 1999-2006 Id Software, Inc. and contributors.
3    For a list of contributors, see the accompanying CONTRIBUTORS file.
4
5    This file is part of GtkRadiant.
6
7    GtkRadiant is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 2 of the License, or
10    (at your option) any later version.
11
12    GtkRadiant is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with GtkRadiant; if not, write to the Free Software
19    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
20  */
21
22 //
23 // Texture Window
24 //
25 // Leonardo Zide (leo@lokigames.com)
26 //
27
28 #include "texwindow.h"
29
30 #include <gtk/gtk.h>
31
32 #include "debugging/debugging.h"
33 #include "warnings.h"
34
35 #include "defaults.h"
36 #include "ifilesystem.h"
37 #include "iundo.h"
38 #include "igl.h"
39 #include "iarchive.h"
40 #include "moduleobserver.h"
41
42 #include <set>
43 #include <string>
44 #include <vector>
45
46 #include <uilib/uilib.h>
47
48 #include "signal/signal.h"
49 #include "math/vector.h"
50 #include "texturelib.h"
51 #include "string/string.h"
52 #include "shaderlib.h"
53 #include "os/file.h"
54 #include "os/path.h"
55 #include "stream/memstream.h"
56 #include "stream/textfilestream.h"
57 #include "stream/stringstream.h"
58 #include "cmdlib.h"
59 #include "texmanip.h"
60 #include "textures.h"
61 #include "convert.h"
62
63 #include "gtkutil/menu.h"
64 #include "gtkutil/nonmodal.h"
65 #include "gtkutil/cursor.h"
66 #include "gtkutil/widget.h"
67 #include "gtkutil/glwidget.h"
68 #include "gtkutil/messagebox.h"
69
70 #include "error.h"
71 #include "map.h"
72 #include "qgl.h"
73 #include "select.h"
74 #include "brush_primit.h"
75 #include "brushmanip.h"
76 #include "patchmanip.h"
77 #include "plugin.h"
78 #include "qe3.h"
79 #include "gtkdlgs.h"
80 #include "gtkmisc.h"
81 #include "mainframe.h"
82 #include "findtexturedialog.h"
83 #include "surfacedialog.h"
84 #include "patchdialog.h"
85 #include "groupdialog.h"
86 #include "preferences.h"
87 #include "shaders.h"
88 #include "commands.h"
89
90 bool TextureBrowser_showWads(){
91         return !string_empty( g_pGameDescription->getKeyValue( "show_wads" ) );
92 }
93
94 void TextureBrowser_queueDraw( TextureBrowser& textureBrowser );
95
96 bool string_equal_start( const char* string, StringRange start ){
97         return string_equal_n( string, start.first, start.last - start.first );
98 }
99
100 typedef std::set<CopiedString> TextureGroups;
101
102 void TextureGroups_addWad( TextureGroups& groups, const char* archive ){
103         if ( extension_equal( path_get_extension( archive ), "wad" ) ) {
104                 groups.insert( archive );
105         }
106 }
107
108 typedef ReferenceCaller<TextureGroups, void(const char*), TextureGroups_addWad> TextureGroupsAddWadCaller;
109
110 namespace
111 {
112 bool g_TextureBrowser_shaderlistOnly = false;
113 bool g_TextureBrowser_fixedSize = true;
114 bool g_TextureBrowser_filterMissing = false;
115 bool g_TextureBrowser_filterFallback = true;
116 bool g_TextureBrowser_enableAlpha = true;
117 }
118
119 CopiedString g_notex;
120 CopiedString g_shadernotex;
121
122 bool isMissing(const char* name);
123
124 bool isNotex(const char* name);
125
126 bool isMissing(const char* name){
127         if ( string_equal( g_notex.c_str(), name ) ) {
128                 return true;
129         }
130         if ( string_equal( g_shadernotex.c_str(), name ) ) {
131                 return true;
132         }
133         return false;
134 }
135
136 bool isNotex(const char* name){
137         if ( string_equal_suffix( name, "/" DEFAULT_NOTEX_BASENAME ) ) {
138                 return true;
139         }
140         if ( string_equal_suffix( name, "/" DEFAULT_SHADERNOTEX_BASENAME ) ) {
141                 return true;
142         }
143         return false;
144 }
145
146 void TextureGroups_addShader( TextureGroups& groups, const char* shaderName ){
147         const char* texture = path_make_relative( shaderName, "textures/" );
148
149         // hide notex / shadernotex images
150         if ( g_TextureBrowser_filterFallback ) {
151                 if ( isNotex( shaderName ) ) {
152                         return;
153                 }
154                 if ( isNotex( texture ) ) {
155                         return;
156                 }
157         }
158
159         if ( texture != shaderName ) {
160                 const char* last = path_remove_directory( texture );
161                 if ( !string_empty( last ) ) {
162                         groups.insert( CopiedString( StringRange( texture, --last ) ) );
163                 }
164         }
165 }
166
167 typedef ReferenceCaller<TextureGroups, void(const char*), TextureGroups_addShader> TextureGroupsAddShaderCaller;
168
169 void TextureGroups_addDirectory( TextureGroups& groups, const char* directory ){
170         groups.insert( directory );
171 }
172
173 typedef ReferenceCaller<TextureGroups, void(const char*), TextureGroups_addDirectory> TextureGroupsAddDirectoryCaller;
174
175 class DeferredAdjustment
176 {
177 gdouble m_value;
178 guint m_handler;
179
180 typedef void ( *ValueChangedFunction )( void* data, gdouble value );
181
182 ValueChangedFunction m_function;
183 void* m_data;
184
185 static gboolean deferred_value_changed( gpointer data ){
186         reinterpret_cast<DeferredAdjustment*>( data )->m_function(
187                 reinterpret_cast<DeferredAdjustment*>( data )->m_data,
188                 reinterpret_cast<DeferredAdjustment*>( data )->m_value
189                 );
190         reinterpret_cast<DeferredAdjustment*>( data )->m_handler = 0;
191         reinterpret_cast<DeferredAdjustment*>( data )->m_value = 0;
192         return FALSE;
193 }
194
195 public:
196 DeferredAdjustment( ValueChangedFunction function, void* data ) : m_value( 0 ), m_handler( 0 ), m_function( function ), m_data( data ){
197 }
198
199 void flush(){
200         if ( m_handler != 0 ) {
201                 g_source_remove( m_handler );
202                 deferred_value_changed( this );
203         }
204 }
205
206 void value_changed( gdouble value ){
207         m_value = value;
208         if ( m_handler == 0 ) {
209                 m_handler = g_idle_add( deferred_value_changed, this );
210         }
211 }
212
213 static void adjustment_value_changed(ui::Adjustment adjustment, DeferredAdjustment* self ){
214         self->value_changed( gtk_adjustment_get_value(adjustment) );
215 }
216 };
217
218
219 class TextureBrowser;
220
221 typedef ReferenceCaller<TextureBrowser, void(), TextureBrowser_queueDraw> TextureBrowserQueueDrawCaller;
222
223 void TextureBrowser_scrollChanged( void* data, gdouble value );
224
225
226 enum StartupShaders
227 {
228         STARTUPSHADERS_NONE = 0,
229         STARTUPSHADERS_COMMON,
230 };
231
232 void TextureBrowser_hideUnusedExport( const Callback<void(bool)> & importer );
233
234 typedef FreeCaller<void(const Callback<void(bool)> &), TextureBrowser_hideUnusedExport> TextureBrowserHideUnusedExport;
235
236 void TextureBrowser_showShadersExport( const Callback<void(bool)> & importer );
237
238 typedef FreeCaller<void(const Callback<void(bool)> &), TextureBrowser_showShadersExport> TextureBrowserShowShadersExport;
239
240 void TextureBrowser_showTexturesExport( const Callback<void(bool)> & importer );
241
242 typedef FreeCaller<void(const Callback<void(bool)> &), TextureBrowser_showTexturesExport> TextureBrowserShowTexturesExport;
243
244 void TextureBrowser_showShaderlistOnly( const Callback<void(bool)> & importer );
245
246 typedef FreeCaller<void(const Callback<void(bool)> &), TextureBrowser_showShaderlistOnly> TextureBrowserShowShaderlistOnlyExport;
247
248 void TextureBrowser_fixedSize( const Callback<void(bool)> & importer );
249
250 typedef FreeCaller<void(const Callback<void(bool)> &), TextureBrowser_fixedSize> TextureBrowserFixedSizeExport;
251
252 void TextureBrowser_filterMissing( const Callback<void(bool)> & importer );
253
254 typedef FreeCaller<void(const Callback<void(bool)> &), TextureBrowser_filterMissing> TextureBrowserFilterMissingExport;
255
256 void TextureBrowser_filterFallback( const Callback<void(bool)> & importer );
257
258 typedef FreeCaller<void(const Callback<void(bool)> &), TextureBrowser_filterFallback> TextureBrowserFilterFallbackExport;
259
260 void TextureBrowser_enableAlpha( const Callback<void(bool)> & importer );
261
262 typedef FreeCaller<void(const Callback<void(bool)> &), TextureBrowser_enableAlpha> TextureBrowserEnableAlphaExport;
263
264 class TextureBrowser
265 {
266 public:
267 int width, height;
268 int originy;
269 int m_nTotalHeight;
270
271 CopiedString shader;
272
273 ui::Window m_parent{ui::null};
274 #ifdef WORKAROUND_MACOS_GTK2_GLWIDGET
275 ui::VBox m_vframe{ui::null};
276 ui::VBox m_vfiller{ui::null};
277 ui::HBox m_hframe{ui::null};
278 ui::HBox m_hfiller{ui::null};
279 #else // !WORKAROUND_MACOS_GTK2_GLWIDGET
280 ui::VBox m_frame{ui::null};
281 #endif // !WORKAROUND_MACOS_GTK2_GLWIDGET
282 ui::GLArea m_gl_widget{ui::null};
283 ui::Widget m_texture_scroll{ui::null};
284 ui::TreeView m_treeViewTree{ui::New};
285 ui::TreeView m_treeViewTags{ui::null};
286 ui::Frame m_tag_frame{ui::null};
287 ui::ListStore m_assigned_store{ui::null};
288 ui::ListStore m_available_store{ui::null};
289 ui::TreeView m_assigned_tree{ui::null};
290 ui::TreeView m_available_tree{ui::null};
291 ui::Widget m_scr_win_tree{ui::null};
292 ui::Widget m_scr_win_tags{ui::null};
293 ui::Widget m_tag_notebook{ui::null};
294 ui::Button m_search_button{ui::null};
295 ui::Widget m_shader_info_item{ui::null};
296
297 std::set<CopiedString> m_all_tags;
298 ui::ListStore m_all_tags_list{ui::null};
299 std::vector<CopiedString> m_copied_tags;
300 std::set<CopiedString> m_found_shaders;
301
302 ToggleItem m_hideunused_item;
303 ToggleItem m_hidenotex_item;
304 ToggleItem m_showshaders_item;
305 ToggleItem m_showtextures_item;
306 ToggleItem m_showshaderlistonly_item;
307 ToggleItem m_fixedsize_item;
308 ToggleItem m_filternotex_item;
309 ToggleItem m_enablealpha_item;
310
311 guint m_sizeHandler;
312 guint m_exposeHandler;
313
314 bool m_heightChanged;
315 bool m_originInvalid;
316
317 DeferredAdjustment m_scrollAdjustment;
318 FreezePointer m_freezePointer;
319
320 Vector3 color_textureback;
321 // the increment step we use against the wheel mouse
322 std::size_t m_mouseWheelScrollIncrement;
323 std::size_t m_textureScale;
324 // make the texture increments match the grid changes
325 bool m_showShaders;
326 bool m_showTextures;
327 bool m_showTextureScrollbar;
328 StartupShaders m_startupShaders;
329 // if true, the texture window will only display in-use shaders
330 // if false, all the shaders in memory are displayed
331 bool m_hideUnused;
332 bool m_rmbSelected;
333 bool m_searchedTags;
334 bool m_tags;
335 // The uniform size (in pixels) that textures are resized to when m_resizeTextures is true.
336 int m_uniformTextureSize;
337 int m_uniformTextureMinSize;
338
339 // Return the display width of a texture in the texture browser
340 /*void getTextureWH( qtexture_t* tex, int *width, int *height ){
341         if ( !g_TextureBrowser_fixedSize ) {
342                 // Don't use uniform size
343                 *width = (int)( tex->width * ( (float)m_textureScale / 100 ) );
344                 *height = (int)( tex->height * ( (float)m_textureScale / 100 ) );
345
346         }
347         else if ( tex->width >= tex->height ) {
348                 // Texture is square, or wider than it is tall
349                 if ( tex->width >= m_uniformTextureSize ){
350                         *width = m_uniformTextureSize;
351                         *height = (int)( m_uniformTextureSize * ( (float)tex->height / tex->width ) );
352                 }
353                 else if ( tex->width <= m_uniformTextureMinSize ){
354                         *width = m_uniformTextureMinSize;
355                         *height = (int)( m_uniformTextureMinSize * ( (float)tex->height / tex->width ) );
356                 }
357                 else {
358                         *width = tex->width;
359                         *height = tex->height;
360                 }
361         }
362         else {
363                 // Texture taller than it is wide
364                 if ( tex->height >= m_uniformTextureSize ){
365                         *height = m_uniformTextureSize;
366                         *width = (int)( m_uniformTextureSize * ( (float)tex->width / tex->height ) );
367                 }
368                 else if ( tex->height <= m_uniformTextureMinSize ){
369                         *height = m_uniformTextureMinSize;
370                         *width = (int)( m_uniformTextureMinSize * ( (float)tex->width / tex->height ) );
371                 }
372                 else {
373                         *width = tex->width;
374                         *height = tex->height;
375                 }
376         }
377 }
378
379 */
380 void getTextureWH( qtexture_t* tex, int &W, int &H ){
381                 // Don't use uniform size
382                 W = (int)( tex->width * ( (float)m_textureScale / 100 ) );
383                 H = (int)( tex->height * ( (float)m_textureScale / 100 ) );
384
385         if ( g_TextureBrowser_fixedSize ){
386                 if      ( W >= H ) {
387                         // Texture is square, or wider than it is tall
388                         if ( W >= m_uniformTextureSize ){
389                                 H = m_uniformTextureSize * H / W;
390                                 W = m_uniformTextureSize;
391                         }
392                         else if ( W <= m_uniformTextureMinSize ){
393                                 H = m_uniformTextureMinSize * H / W;
394                                 W = m_uniformTextureMinSize;
395                         }
396                 }
397                 else {
398                         // Texture taller than it is wide
399                         if ( H >= m_uniformTextureSize ){
400                                 W = m_uniformTextureSize * W / H;
401                                 H = m_uniformTextureSize;
402                         }
403                         else if ( H <= m_uniformTextureMinSize ){
404                                 W = m_uniformTextureMinSize * W / H;
405                                 H = m_uniformTextureMinSize;
406                         }
407                 }
408         }
409 }
410
411 TextureBrowser() :
412         m_texture_scroll( ui::null ),
413         m_hideunused_item( TextureBrowserHideUnusedExport() ),
414         m_hidenotex_item( TextureBrowserFilterFallbackExport() ),
415         m_showshaders_item( TextureBrowserShowShadersExport() ),
416         m_showtextures_item( TextureBrowserShowTexturesExport() ),
417         m_showshaderlistonly_item( TextureBrowserShowShaderlistOnlyExport() ),
418         m_fixedsize_item( TextureBrowserFixedSizeExport() ),
419         m_filternotex_item( TextureBrowserFilterMissingExport() ),
420         m_enablealpha_item( TextureBrowserEnableAlphaExport() ),
421         m_heightChanged( true ),
422         m_originInvalid( true ),
423         m_scrollAdjustment( TextureBrowser_scrollChanged, this ),
424         color_textureback( 0.25f, 0.25f, 0.25f ),
425         m_mouseWheelScrollIncrement( 64 ),
426         m_textureScale( 50 ),
427         m_showShaders( true ),
428         m_showTextures( true ),
429         m_showTextureScrollbar( true ),
430         m_startupShaders( STARTUPSHADERS_NONE ),
431         m_hideUnused( false ),
432         m_rmbSelected( false ),
433         m_searchedTags( false ),
434         m_tags( false ),
435         m_uniformTextureSize( 160 ),
436         m_uniformTextureMinSize( 48 ){
437 }
438 };
439
440 void ( *TextureBrowser_textureSelected )( const char* shader );
441
442
443 void TextureBrowser_updateScroll( TextureBrowser& textureBrowser );
444
445
446 const char* TextureBrowser_getCommonShadersName(){
447         const char* value = g_pGameDescription->getKeyValue( "common_shaders_name" );
448         if ( !string_empty( value ) ) {
449                 return value;
450         }
451         return "Common";
452 }
453
454 const char* TextureBrowser_getCommonShadersDir(){
455         const char* value = g_pGameDescription->getKeyValue( "common_shaders_dir" );
456         if ( !string_empty( value ) ) {
457                 return value;
458         }
459         return "common/";
460 }
461
462 inline int TextureBrowser_fontHeight( TextureBrowser& textureBrowser ){
463         return GlobalOpenGL().m_font->getPixelHeight();
464 }
465
466 const char* TextureBrowser_GetSelectedShader( TextureBrowser& textureBrowser ){
467         return textureBrowser.shader.c_str();
468 }
469
470 void TextureBrowser_SetStatus( TextureBrowser& textureBrowser, const char* name ){
471         IShader* shader = QERApp_Shader_ForName( name );
472         qtexture_t* q = shader->getTexture();
473         StringOutputStream strTex( 256 );
474         strTex << name << " W: " << Unsigned( q->width ) << " H: " << Unsigned( q->height );
475         shader->DecRef();
476         g_pParentWnd->SetStatusText( g_pParentWnd->m_texture_status, strTex.c_str() );
477 }
478
479 void TextureBrowser_Focus( TextureBrowser& textureBrowser, const char* name );
480
481 void TextureBrowser_SetSelectedShader( TextureBrowser& textureBrowser, const char* shader ){
482         textureBrowser.shader = shader;
483         TextureBrowser_SetStatus( textureBrowser, shader );
484         TextureBrowser_Focus( textureBrowser, shader );
485
486         if ( FindTextureDialog_isOpen() ) {
487                 FindTextureDialog_selectTexture( shader );
488         }
489
490         // disable the menu item "shader info" if no shader was selected
491         IShader* ishader = QERApp_Shader_ForName( shader );
492         CopiedString filename = ishader->getShaderFileName();
493
494         if ( filename.empty() ) {
495                 if ( textureBrowser.m_shader_info_item != NULL ) {
496                         gtk_widget_set_sensitive( textureBrowser.m_shader_info_item, FALSE );
497                 }
498         }
499         else {
500                 gtk_widget_set_sensitive( textureBrowser.m_shader_info_item, TRUE );
501         }
502
503         ishader->DecRef();
504 }
505
506
507 CopiedString g_TextureBrowser_currentDirectory;
508
509 /*
510    ============================================================================
511
512    TEXTURE LAYOUT
513
514    TTimo: now based on a rundown through all the shaders
515    NOTE: we expect the Active shaders count doesn't change during a Texture_StartPos .. Texture_NextPos cycle
516    otherwise we may need to rely on a list instead of an array storage
517    ============================================================================
518  */
519
520 class TextureLayout
521 {
522 public:
523 // texture layout functions
524 // TTimo: now based on shaders
525 int current_x, current_y, current_row;
526 };
527
528 void Texture_StartPos( TextureLayout& layout ){
529         layout.current_x = 8;
530         layout.current_y = -8;
531         layout.current_row = 0;
532 }
533
534 void Texture_NextPos( TextureBrowser& textureBrowser, TextureLayout& layout, qtexture_t* current_texture, int *x, int *y ){
535         qtexture_t* q = current_texture;
536
537         int nWidth, nHeight;
538         textureBrowser.getTextureWH( q, nWidth, nHeight );
539         if ( layout.current_x + nWidth > textureBrowser.width - 8 && layout.current_row ) { // go to the next row unless the texture is the first on the row
540                 layout.current_x = 8;
541                 layout.current_y -= layout.current_row + TextureBrowser_fontHeight( textureBrowser ) + 4;
542                 layout.current_row = 0;
543         }
544
545         *x = layout.current_x;
546         *y = layout.current_y;
547
548         // Is our texture larger than the row? If so, grow the
549         // row height to match it
550
551         if ( layout.current_row < nHeight ) {
552                 layout.current_row = nHeight;
553         }
554
555         // never go less than 96, or the names get all crunched up
556         layout.current_x += nWidth < 96 ? 96 : nWidth;
557         layout.current_x += 8;
558 }
559
560 bool TextureSearch_IsShown( const char* name ){
561         std::set<CopiedString>::iterator iter;
562
563         iter = GlobalTextureBrowser().m_found_shaders.find( name );
564
565         if ( iter == GlobalTextureBrowser().m_found_shaders.end() ) {
566                 return false;
567         }
568         else {
569                 return true;
570         }
571 }
572
573 // if texture_showinuse jump over non in-use textures
574 bool Texture_IsShown( IShader* shader, bool show_shaders, bool show_textures, bool hideUnused ){
575         // filter missing shaders
576         // ugly: filter on built-in fallback name after substitution
577         if ( g_TextureBrowser_filterMissing ) {
578                 if ( isMissing( shader->getTexture()->name ) ) {
579                         return false;
580                 }
581         }
582         // filter the fallback (notex/shadernotex) for missing shaders or editor image
583         if ( g_TextureBrowser_filterFallback ) {
584                 if ( isNotex( shader->getName() ) ) {
585                         return false;
586                 }
587                 if ( isNotex( shader->getTexture()->name ) ) {
588                         return false;
589                 }
590         }
591
592         if ( g_TextureBrowser_currentDirectory == "Untagged" ) {
593                 std::set<CopiedString>::iterator iter;
594
595                 iter = GlobalTextureBrowser().m_found_shaders.find( shader->getName() );
596
597                 if ( iter == GlobalTextureBrowser().m_found_shaders.end() ) {
598                         return false;
599                 }
600                 else {
601                         return true;
602                 }
603         }
604
605         if ( !shader_equal_prefix( shader->getName(), "textures/" ) ) {
606                 return false;
607         }
608
609         if ( !show_shaders && !shader->IsDefault() ) {
610                 return false;
611         }
612
613         if ( !show_textures && shader->IsDefault() ) {
614                 return false;
615         }
616
617         if ( hideUnused && !shader->IsInUse() ) {
618                 return false;
619         }
620
621         if ( GlobalTextureBrowser().m_searchedTags ) {
622                 if ( !TextureSearch_IsShown( shader->getName() ) ) {
623                         return false;
624                 }
625                 else {
626                         return true;
627                 }
628         }
629         else {
630                 if ( TextureBrowser_showWads() )
631                 {
632                         if ( g_TextureBrowser_currentDirectory != ""
633                                 && !string_equal( shader->getWadName(), g_TextureBrowser_currentDirectory.c_str() ) )
634                         {
635                                 return false;
636                         }
637                 }
638                 else if ( !shader_equal_prefix( shader_get_textureName( shader->getName() ), g_TextureBrowser_currentDirectory.c_str() ) ) {
639                         return false;
640                 }
641         }
642
643         return true;
644 }
645
646 void TextureBrowser_heightChanged( TextureBrowser& textureBrowser ){
647         textureBrowser.m_heightChanged = true;
648
649         TextureBrowser_updateScroll( textureBrowser );
650         TextureBrowser_queueDraw( textureBrowser );
651 }
652
653 void TextureBrowser_evaluateHeight( TextureBrowser& textureBrowser ){
654         if ( textureBrowser.m_heightChanged ) {
655                 textureBrowser.m_heightChanged = false;
656
657                 textureBrowser.m_nTotalHeight = 0;
658
659                 TextureLayout layout;
660                 Texture_StartPos( layout );
661                 for ( QERApp_ActiveShaders_IteratorBegin(); !QERApp_ActiveShaders_IteratorAtEnd(); QERApp_ActiveShaders_IteratorIncrement() )
662                 {
663                         IShader* shader = QERApp_ActiveShaders_IteratorCurrent();
664
665                         if ( !Texture_IsShown( shader, textureBrowser.m_showShaders, textureBrowser.m_showTextures, textureBrowser.m_hideUnused ) ) {
666                                 continue;
667                         }
668
669                         int x, y;
670                         Texture_NextPos( textureBrowser, layout, shader->getTexture(), &x, &y );
671                         int nWidth, nHeight;
672                         textureBrowser.getTextureWH( shader->getTexture(), nWidth, nHeight );
673                         textureBrowser.m_nTotalHeight = std::max( textureBrowser.m_nTotalHeight, abs( layout.current_y ) + TextureBrowser_fontHeight( textureBrowser ) + nHeight + 4 );
674                 }
675         }
676 }
677
678 int TextureBrowser_TotalHeight( TextureBrowser& textureBrowser ){
679         TextureBrowser_evaluateHeight( textureBrowser );
680         return textureBrowser.m_nTotalHeight;
681 }
682
683 inline const int& min_int( const int& left, const int& right ){
684         return std::min( left, right );
685 }
686
687 void TextureBrowser_clampOriginY( TextureBrowser& textureBrowser ){
688         if ( textureBrowser.originy > 0 ) {
689                 textureBrowser.originy = 0;
690         }
691         int lower = min_int( textureBrowser.height - TextureBrowser_TotalHeight( textureBrowser ), 0 );
692         if ( textureBrowser.originy < lower ) {
693                 textureBrowser.originy = lower;
694         }
695 }
696
697 int TextureBrowser_getOriginY( TextureBrowser& textureBrowser ){
698         if ( textureBrowser.m_originInvalid ) {
699                 textureBrowser.m_originInvalid = false;
700                 TextureBrowser_clampOriginY( textureBrowser );
701                 TextureBrowser_updateScroll( textureBrowser );
702         }
703         return textureBrowser.originy;
704 }
705
706 void TextureBrowser_setOriginY( TextureBrowser& textureBrowser, int originy ){
707         textureBrowser.originy = originy;
708         TextureBrowser_clampOriginY( textureBrowser );
709         TextureBrowser_updateScroll( textureBrowser );
710         TextureBrowser_queueDraw( textureBrowser );
711 }
712
713
714 Signal0 g_activeShadersChangedCallbacks;
715
716 void TextureBrowser_addActiveShadersChangedCallback( const SignalHandler& handler ){
717         g_activeShadersChangedCallbacks.connectLast( handler );
718 }
719
720 void TextureBrowser_constructTreeStore();
721
722 class ShadersObserver : public ModuleObserver
723 {
724 Signal0 m_realiseCallbacks;
725 public:
726 void realise(){
727         m_realiseCallbacks();
728         /* texturebrowser tree update on vfs restart */
729 //      TextureBrowser_constructTreeStore();
730 }
731
732 void unrealise(){
733 }
734
735 void insert( const SignalHandler& handler ){
736         m_realiseCallbacks.connectLast( handler );
737 }
738 };
739
740 namespace
741 {
742 ShadersObserver g_ShadersObserver;
743 }
744
745 void TextureBrowser_addShadersRealiseCallback( const SignalHandler& handler ){
746         g_ShadersObserver.insert( handler );
747 }
748
749 void TextureBrowser_activeShadersChanged( TextureBrowser& textureBrowser ){
750         TextureBrowser_heightChanged( textureBrowser );
751         textureBrowser.m_originInvalid = true;
752
753         g_activeShadersChangedCallbacks();
754 }
755
756 struct TextureBrowser_ShowScrollbar {
757         static void Export(const TextureBrowser &self, const Callback<void(bool)> &returnz) {
758                 returnz(self.m_showTextureScrollbar);
759         }
760
761         static void Import(TextureBrowser &self, bool value) {
762                 self.m_showTextureScrollbar = value;
763                 if (self.m_texture_scroll) {
764                         self.m_texture_scroll.visible(self.m_showTextureScrollbar);
765                         TextureBrowser_updateScroll(self);
766                 }
767         }
768 };
769
770
771 /*
772    ==============
773    TextureBrowser_ShowDirectory
774    relies on texture_directory global for the directory to use
775    1) Load the shaders for the given directory
776    2) Scan the remaining texture, load them and assign them a default shader (the "noshader" shader)
777    NOTE: when writing a texture plugin, or some texture extensions, this function may need to be overriden, and made
778    available through the IShaders interface
779    NOTE: for texture window layout:
780    all shaders are stored with alphabetical order after load
781    previously loaded and displayed stuff is hidden, only in-use and newly loaded is shown
782    ( the GL textures are not flushed though)
783    ==============
784  */
785
786 bool endswith( const char *haystack, const char *needle ){
787         size_t lh = strlen( haystack );
788         size_t ln = strlen( needle );
789         if ( lh < ln ) {
790                 return false;
791         }
792         return !memcmp( haystack + ( lh - ln ), needle, ln );
793 }
794
795 bool texture_name_ignore( const char* name ){
796         StringOutputStream strTemp( string_length( name ) );
797         strTemp << LowerCase( name );
798
799         return
800                 endswith( strTemp.c_str(), ".specular" ) ||
801                 endswith( strTemp.c_str(), ".glow" ) ||
802                 endswith( strTemp.c_str(), ".bump" ) ||
803                 endswith( strTemp.c_str(), ".diffuse" ) ||
804                 endswith( strTemp.c_str(), ".blend" ) ||
805                 endswith( strTemp.c_str(), ".alpha" ) ||
806                 endswith( strTemp.c_str(), "_alpha" ) ||
807                 /* Quetoo */
808                 endswith( strTemp.c_str(), "_h" ) ||
809                 endswith( strTemp.c_str(), "_local" ) ||
810                 endswith( strTemp.c_str(), "_nm" ) ||
811                 endswith( strTemp.c_str(), "_s" ) ||
812                 /* DarkPlaces */
813                 endswith( strTemp.c_str(), "_bump" ) ||
814                 endswith( strTemp.c_str(), "_glow" ) ||
815                 endswith( strTemp.c_str(), "_gloss" ) ||
816                 endswith( strTemp.c_str(), "_luma" ) ||
817                 endswith( strTemp.c_str(), "_norm" ) ||
818                 endswith( strTemp.c_str(), "_pants" ) ||
819                 endswith( strTemp.c_str(), "_shirt" ) ||
820                 endswith( strTemp.c_str(), "_reflect" ) ||
821                 /* Unvanquished */
822                 endswith( strTemp.c_str(), "_d" ) ||
823                 endswith( strTemp.c_str(), "_n" ) ||
824                 endswith( strTemp.c_str(), "_p" ) ||
825                 endswith( strTemp.c_str(), "_g" ) ||
826                 endswith( strTemp.c_str(), "_a" ) ||
827                 0;
828 }
829
830 class LoadShaderVisitor : public Archive::Visitor
831 {
832 public:
833 void visit( const char* name ){
834         IShader* shader = QERApp_Shader_ForName( CopiedString( StringRange( name, path_get_filename_base_end( name ) ) ).c_str() );
835         shader->DecRef();
836         shader->setWadName( g_TextureBrowser_currentDirectory.c_str() );
837 }
838 };
839
840 void TextureBrowser_SetHideUnused( TextureBrowser& textureBrowser, bool hideUnused );
841
842 ui::Widget g_page_textures{ui::null};
843
844 void TextureBrowser_toggleShow(){
845         GroupDialog_showPage( g_page_textures );
846 }
847
848
849 void TextureBrowser_updateTitle(){
850         GroupDialog_updatePageTitle( g_page_textures );
851 }
852
853
854 class TextureCategoryLoadShader
855 {
856 const char* m_directory;
857 std::size_t& m_count;
858 public:
859 using func = void(const char *);
860
861 TextureCategoryLoadShader( const char* directory, std::size_t& count )
862         : m_directory( directory ), m_count( count ){
863         m_count = 0;
864 }
865
866 void operator()( const char* name ) const {
867         if ( shader_equal_prefix( name, "textures/" )
868                  && shader_equal_prefix( name + string_length( "textures/" ), m_directory ) ) {
869                 ++m_count;
870                 // request the shader, this will load the texture if needed
871                 // this Shader_ForName call is a kind of hack
872                 IShader *pFoo = QERApp_Shader_ForName( name );
873                 pFoo->DecRef();
874         }
875 }
876 };
877
878 void TextureDirectory_loadTexture( const char* directory, const char* texture ){
879         // Doom3-like dds/ prefix (used by DarkPlaces).
880         // When we list dds/textures/ folder,
881         // store the texture names without dds/ prefix.
882         if ( !strncmp( "dds/", directory, 4 ) )
883         {
884                 directory = &directory[ 4 ];
885         }
886
887         StringOutputStream name( 256 );
888         name << directory << StringRange( texture, path_get_filename_base_end( texture ) );
889
890         if ( texture_name_ignore( name.c_str() ) ) {
891                 return;
892         }
893
894         if ( !shader_valid( name.c_str() ) ) {
895                 globalOutputStream() << "Skipping invalid texture name: [" << name.c_str() << "]\n";
896                 return;
897         }
898
899         // if a texture is already in use to represent a shader, ignore it
900         IShader* shader = QERApp_Shader_ForName( name.c_str() );
901         shader->DecRef();
902 }
903
904 typedef ConstPointerCaller<char, void(const char*), TextureDirectory_loadTexture> TextureDirectoryLoadTextureCaller;
905
906 class LoadTexturesByTypeVisitor : public ImageModules::Visitor
907 {
908 const char* m_dirstring;
909 public:
910 LoadTexturesByTypeVisitor( const char* dirstring )
911         : m_dirstring( dirstring ){
912 }
913
914 void visit( const char* minor, const _QERPlugImageTable& table ) const {
915         GlobalFileSystem().forEachFile( m_dirstring, minor, TextureDirectoryLoadTextureCaller( m_dirstring ) );
916 }
917 };
918
919 void TextureBrowser_ShowDirectory( TextureBrowser& textureBrowser, const char* directory ){
920         if ( TextureBrowser_showWads() ) {
921                 g_TextureBrowser_currentDirectory = directory;
922                 TextureBrowser_heightChanged( textureBrowser );
923
924                 Archive* archive = GlobalFileSystem().getArchive( directory );
925                 if ( archive != nullptr )
926                 {
927                 LoadShaderVisitor visitor;
928                 archive->forEachFile( Archive::VisitorFunc( visitor, Archive::eFiles, 0 ), "textures/" );
929
930                         // Doom3-like dds/ prefix (used by DarkPlaces).
931                         archive->forEachFile( Archive::VisitorFunc( visitor, Archive::eFiles, 0 ), "dds/textures/" );
932                 }
933                 else if ( extension_equal_i( path_get_extension( directory ), "wad" ) )
934                 {
935                         globalErrorStream() << "Failed to load " << directory << "\n";
936                 }
937         }
938         else
939         {
940                 g_TextureBrowser_currentDirectory = directory;
941                 TextureBrowser_heightChanged( textureBrowser );
942
943                 std::size_t shaders_count;
944                 GlobalShaderSystem().foreachShaderName(makeCallback( TextureCategoryLoadShader( directory, shaders_count ) ) );
945                 globalOutputStream() << "Showing " << Unsigned( shaders_count ) << " shaders.\n";
946
947                 if ( g_pGameDescription->mGameType != "doom3" ) {
948                         // load remaining texture files
949
950                         StringOutputStream dirstring( 64 );
951                         dirstring << "textures/" << directory;
952
953                         {
954                                 LoadTexturesByTypeVisitor visitor( dirstring.c_str() );
955                                 Radiant_getImageModules().foreachModule( visitor );
956                         }
957
958                         // Doom3-like dds/ prefix (used by DarkPlaces).
959                         dirstring.clear();
960                         dirstring << "dds/textures/" << directory;
961
962                         {
963                                 LoadTexturesByTypeVisitor visitor( dirstring.c_str() );
964                                 Radiant_getImageModules().foreachModule( visitor );
965                         }
966                 }
967         }
968
969         // we'll display the newly loaded textures + all the ones already in use
970         TextureBrowser_SetHideUnused( textureBrowser, false );
971
972         TextureBrowser_updateTitle();
973 }
974
975 void TextureBrowser_ShowTagSearchResult( TextureBrowser& textureBrowser, const char* directory ){
976         g_TextureBrowser_currentDirectory = directory;
977         TextureBrowser_heightChanged( textureBrowser );
978
979         std::size_t shaders_count;
980         GlobalShaderSystem().foreachShaderName(makeCallback( TextureCategoryLoadShader( directory, shaders_count ) ) );
981         globalOutputStream() << "Showing " << Unsigned( shaders_count ) << " shaders.\n";
982
983         if ( g_pGameDescription->mGameType != "doom3" ) {
984                 // load remaining texture files
985                 StringOutputStream dirstring( 64 );
986                 dirstring << "textures/" << directory;
987
988                 {
989                         LoadTexturesByTypeVisitor visitor( dirstring.c_str() );
990                         Radiant_getImageModules().foreachModule( visitor );
991                 }
992
993                 // Doom3-like dds/ prefix (used by DarkPlaces).
994                 dirstring.clear();
995                 dirstring << "dds/textures/" << directory;
996
997                 {
998                         LoadTexturesByTypeVisitor visitor( dirstring.c_str() );
999                         Radiant_getImageModules().foreachModule( visitor );
1000                 }
1001         }
1002
1003         // we'll display the newly loaded textures + all the ones already in use
1004         TextureBrowser_SetHideUnused( textureBrowser, false );
1005 }
1006
1007
1008 bool TextureBrowser_hideUnused();
1009
1010 void TextureBrowser_hideUnusedExport( const Callback<void(bool)> & importer ){
1011         importer( TextureBrowser_hideUnused() );
1012 }
1013
1014 typedef FreeCaller<void(const Callback<void(bool)> &), TextureBrowser_hideUnusedExport> TextureBrowserHideUnusedExport;
1015
1016 void TextureBrowser_showShadersExport( const Callback<void(bool)> & importer ){
1017         importer( GlobalTextureBrowser().m_showShaders );
1018 }
1019
1020 typedef FreeCaller<void(const Callback<void(bool)> &), TextureBrowser_showShadersExport> TextureBrowserShowShadersExport;
1021
1022 void TextureBrowser_showTexturesExport( const Callback<void(bool)> & importer ){
1023         importer( GlobalTextureBrowser().m_showTextures );
1024 }
1025
1026 typedef FreeCaller<void(const Callback<void(bool)> &), TextureBrowser_showTexturesExport> TextureBrowserShowTexturesExport;
1027
1028 void TextureBrowser_showShaderlistOnly( const Callback<void(bool)> & importer ){
1029         importer( g_TextureBrowser_shaderlistOnly );
1030 }
1031
1032 typedef FreeCaller<void(const Callback<void(bool)> &), TextureBrowser_showShaderlistOnly> TextureBrowserShowShaderlistOnlyExport;
1033
1034 void TextureBrowser_fixedSize( const Callback<void(bool)> & importer ){
1035         importer( g_TextureBrowser_fixedSize );
1036 }
1037
1038 typedef FreeCaller<void(const Callback<void(bool)> &), TextureBrowser_fixedSize> TextureBrowser_FixedSizeExport;
1039
1040 void TextureBrowser_filterMissing( const Callback<void(bool)> & importer ){
1041         importer( g_TextureBrowser_filterMissing );
1042 }
1043
1044 typedef FreeCaller<void(const Callback<void(bool)> &), TextureBrowser_filterMissing> TextureBrowser_filterMissingExport;
1045
1046 void TextureBrowser_filterFallback( const Callback<void(bool)> & importer ){
1047         importer( g_TextureBrowser_filterFallback );
1048 }
1049
1050 typedef FreeCaller<void(const Callback<void(bool)> &), TextureBrowser_filterFallback> TextureBrowser_filterFallbackExport;
1051
1052 void TextureBrowser_enableAlpha( const Callback<void(bool)> & importer ){
1053         importer( g_TextureBrowser_enableAlpha );
1054 }
1055
1056 typedef FreeCaller<void(const Callback<void(bool)> &), TextureBrowser_enableAlpha> TextureBrowser_enableAlphaExport;
1057
1058 void TextureBrowser_SetHideUnused( TextureBrowser& textureBrowser, bool hideUnused ){
1059         if ( hideUnused ) {
1060                 textureBrowser.m_hideUnused = true;
1061         }
1062         else
1063         {
1064                 textureBrowser.m_hideUnused = false;
1065         }
1066
1067         textureBrowser.m_hideunused_item.update();
1068
1069         TextureBrowser_heightChanged( textureBrowser );
1070         textureBrowser.m_originInvalid = true;
1071 }
1072
1073 void TextureBrowser_ShowStartupShaders( TextureBrowser& textureBrowser ){
1074         if ( textureBrowser.m_startupShaders == STARTUPSHADERS_COMMON ) {
1075                 TextureBrowser_ShowDirectory( textureBrowser, TextureBrowser_getCommonShadersDir() );
1076         }
1077 }
1078
1079
1080 //++timo NOTE: this is a mix of Shader module stuff and texture explorer
1081 // it might need to be split in parts or moved out .. dunno
1082 // scroll origin so the specified texture is completely on screen
1083 // if current texture is not displayed, nothing is changed
1084 void TextureBrowser_Focus( TextureBrowser& textureBrowser, const char* name ){
1085         TextureLayout layout;
1086         // scroll origin so the texture is completely on screen
1087         Texture_StartPos( layout );
1088
1089         for ( QERApp_ActiveShaders_IteratorBegin(); !QERApp_ActiveShaders_IteratorAtEnd(); QERApp_ActiveShaders_IteratorIncrement() )
1090         {
1091                 IShader* shader = QERApp_ActiveShaders_IteratorCurrent();
1092
1093                 if ( !Texture_IsShown( shader, textureBrowser.m_showShaders, textureBrowser.m_showTextures, textureBrowser.m_hideUnused ) ) {
1094                         continue;
1095                 }
1096
1097                 int x, y;
1098                 Texture_NextPos( textureBrowser, layout, shader->getTexture(), &x, &y );
1099                 qtexture_t* q = shader->getTexture();
1100                 if ( !q ) {
1101                         break;
1102                 }
1103
1104                 // we have found when texdef->name and the shader name match
1105                 // NOTE: as everywhere else for our comparisons, we are not case sensitive
1106                 if ( shader_equal( name, shader->getName() ) ) {
1107                         int textureHeight = (int)( q->height * ( (float)textureBrowser.m_textureScale / 100 ) )
1108                                                                 + 2 * TextureBrowser_fontHeight( textureBrowser );
1109
1110                         int originy = TextureBrowser_getOriginY( textureBrowser );
1111                         if ( y > originy ) {
1112                                 originy = y;
1113                         }
1114
1115                         if ( y - textureHeight < originy - textureBrowser.height ) {
1116                                 originy = ( y - textureHeight ) + textureBrowser.height;
1117                         }
1118
1119                         TextureBrowser_setOriginY( textureBrowser, originy );
1120                         return;
1121                 }
1122         }
1123 }
1124
1125 IShader* Texture_At( TextureBrowser& textureBrowser, int mx, int my ){
1126         my += TextureBrowser_getOriginY( textureBrowser ) - textureBrowser.height;
1127
1128         TextureLayout layout;
1129         Texture_StartPos( layout );
1130         for ( QERApp_ActiveShaders_IteratorBegin(); !QERApp_ActiveShaders_IteratorAtEnd(); QERApp_ActiveShaders_IteratorIncrement() )
1131         {
1132                 IShader* shader = QERApp_ActiveShaders_IteratorCurrent();
1133
1134                 if ( !Texture_IsShown( shader, textureBrowser.m_showShaders, textureBrowser.m_showTextures, textureBrowser.m_hideUnused ) ) {
1135                         continue;
1136                 }
1137
1138                 int x, y;
1139                 Texture_NextPos( textureBrowser, layout, shader->getTexture(), &x, &y );
1140                 qtexture_t  *q = shader->getTexture();
1141                 if ( !q ) {
1142                         break;
1143                 }
1144
1145                 int nWidth, nHeight;
1146                 textureBrowser.getTextureWH( q, nWidth, nHeight );
1147                 if ( mx > x && mx - x < nWidth
1148                          && my < y && y - my < nHeight + TextureBrowser_fontHeight( textureBrowser ) ) {
1149                         return shader;
1150                 }
1151         }
1152
1153         return 0;
1154 }
1155
1156 /*
1157    ==============
1158    SelectTexture
1159
1160    By mouse click
1161    ==============
1162  */
1163 void SelectTexture( TextureBrowser& textureBrowser, int mx, int my, bool bShift ){
1164         IShader* shader = Texture_At( textureBrowser, mx, my );
1165         if ( shader != 0 ) {
1166                 if ( bShift ) {
1167                         if ( shader->IsDefault() ) {
1168                                 globalOutputStream() << "ERROR: " << shader->getName() << " is not a shader, it's a texture.\n";
1169                         }
1170                         else{
1171                                 ViewShader( shader->getShaderFileName(), shader->getName() );
1172                         }
1173                 }
1174                 else
1175                 {
1176                         TextureBrowser_SetSelectedShader( textureBrowser, shader->getName() );
1177                         TextureBrowser_textureSelected( shader->getName() );
1178
1179                         if ( !FindTextureDialog_isOpen() && !textureBrowser.m_rmbSelected ) {
1180                                 UndoableCommand undo( "textureNameSetSelected" );
1181                                 Select_SetShader( shader->getName() );
1182                         }
1183                 }
1184         }
1185 }
1186
1187 /*
1188    ============================================================================
1189
1190    MOUSE ACTIONS
1191
1192    ============================================================================
1193  */
1194
1195 void TextureBrowser_trackingDelta( int x, int y, unsigned int state, void* data ){
1196         TextureBrowser& textureBrowser = *reinterpret_cast<TextureBrowser*>( data );
1197         if ( y != 0 ) {
1198                 int scale = 1;
1199
1200                 if ( state & GDK_SHIFT_MASK ) {
1201                         scale = 4;
1202                 }
1203
1204                 int originy = TextureBrowser_getOriginY( textureBrowser );
1205                 originy += y * scale;
1206                 TextureBrowser_setOriginY( textureBrowser, originy );
1207         }
1208 }
1209
1210 void TextureBrowser_Tracking_MouseDown( TextureBrowser& textureBrowser ){
1211         textureBrowser.m_freezePointer.freeze_pointer( textureBrowser.m_gl_widget, TextureBrowser_trackingDelta, &textureBrowser );
1212 }
1213
1214 void TextureBrowser_Tracking_MouseUp( TextureBrowser& textureBrowser ){
1215         textureBrowser.m_freezePointer.unfreeze_pointer( textureBrowser.m_gl_widget );
1216 }
1217
1218 void TextureBrowser_Selection_MouseDown( TextureBrowser& textureBrowser, guint32 flags, int pointx, int pointy ){
1219         SelectTexture( textureBrowser, pointx, textureBrowser.height - 1 - pointy, ( flags & GDK_SHIFT_MASK ) != 0 );
1220 }
1221
1222 /*
1223    ============================================================================
1224
1225    DRAWING
1226
1227    ============================================================================
1228  */
1229
1230 /*
1231    ============
1232    Texture_Draw
1233    TTimo: relying on the shaders list to display the textures
1234    we must query all qtexture_t* to manage and display through the IShaders interface
1235    this allows a plugin to completely override the texture system
1236    ============
1237  */
1238 void Texture_Draw( TextureBrowser& textureBrowser ){
1239         int originy = TextureBrowser_getOriginY( textureBrowser );
1240
1241         glClearColor( textureBrowser.color_textureback[0],
1242                                   textureBrowser.color_textureback[1],
1243                                   textureBrowser.color_textureback[2],
1244                                   0 );
1245
1246         glViewport( 0, 0, textureBrowser.width, textureBrowser.height );
1247         glMatrixMode( GL_PROJECTION );
1248         glLoadIdentity();
1249
1250         glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
1251         glDisable( GL_DEPTH_TEST );
1252
1253         //glDisable( GL_BLEND );
1254         if ( g_TextureBrowser_enableAlpha ) {
1255                 glEnable( GL_BLEND );
1256                 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1257         }
1258         else {
1259                 glDisable( GL_BLEND );
1260         }
1261
1262         glOrtho( 0, textureBrowser.width, originy - textureBrowser.height, originy, -100, 100 );
1263         glEnable( GL_TEXTURE_2D );
1264
1265         glPolygonMode( GL_FRONT_AND_BACK, GL_FILL );
1266
1267         int last_y = 0, last_height = 0;
1268
1269         TextureLayout layout;
1270         Texture_StartPos( layout );
1271         for ( QERApp_ActiveShaders_IteratorBegin(); !QERApp_ActiveShaders_IteratorAtEnd(); QERApp_ActiveShaders_IteratorIncrement() )
1272         {
1273                 IShader* shader = QERApp_ActiveShaders_IteratorCurrent();
1274
1275                 if ( !Texture_IsShown( shader, textureBrowser.m_showShaders, textureBrowser.m_showTextures, textureBrowser.m_hideUnused ) ) {
1276                         continue;
1277                 }
1278
1279                 int x, y;
1280                 Texture_NextPos( textureBrowser, layout, shader->getTexture(), &x, &y );
1281                 qtexture_t *q = shader->getTexture();
1282                 if ( !q ) {
1283                         break;
1284                 }
1285
1286                 int nWidth, nHeight;
1287                 textureBrowser.getTextureWH( q, nWidth, nHeight );
1288
1289                 if ( y != last_y ) {
1290                         last_y = y;
1291                         last_height = 0;
1292                 }
1293                 last_height = std::max( nHeight, last_height );
1294
1295                 // Is this texture visible?
1296                 if ( ( y - nHeight - TextureBrowser_fontHeight( textureBrowser ) < originy )
1297                          && ( y > originy - textureBrowser.height ) ) {
1298                         // borders rules:
1299                         // if it's the current texture, draw a thick red line, else:
1300                         // shaders have a white border, simple textures don't
1301                         // if !texture_showinuse: (some textures displayed may not be in use)
1302                         // draw an additional square around with 0.5 1 0.5 color
1303                         glLineWidth( 1 );
1304                         // shader border:
1305                         if ( !shader->IsDefault() ) {
1306                         //real 1px white/black stipple
1307                                 glColor3f( 0, 0, 0 );
1308                                 glDisable( GL_TEXTURE_2D );
1309
1310                                 float xf = (float)x;
1311                                 float yf = (float)( y - TextureBrowser_fontHeight( textureBrowser ) );
1312                                 glBegin( GL_LINE_LOOP );
1313                                 glVertex2f( xf - 1.5,yf + 1.5 );
1314                                 glVertex2f( xf - 1.5,yf - nHeight - 1.5 );
1315                                 glVertex2f( xf + 1.5 + nWidth,yf - nHeight - 1.5 );
1316                                 glVertex2f( xf + 1.5 + nWidth,yf + 1.5 );
1317
1318                                 glEnd();
1319
1320                                 glEnable( GL_LINE_STIPPLE );
1321                                 glLineStipple( 1, 0x0FFF );
1322
1323                                 glBegin( GL_LINE_LOOP );
1324                                 glColor3f( 1, 1, 1 );
1325
1326                                 glVertex2f( xf - 1.5,yf + 1.5 );
1327                                 glVertex2f( xf - 1.5,yf - nHeight - 1.5 );
1328                                 glVertex2f( xf + 1.5 + nWidth,yf - nHeight - 1.5 );
1329                                 glVertex2f( xf + 1.5 + nWidth,yf + 1.5 );
1330
1331                                 glEnd();
1332                                 glDisable( GL_LINE_STIPPLE );
1333                                 glEnable( GL_TEXTURE_2D );
1334
1335                         }
1336                         if ( shader_equal( TextureBrowser_GetSelectedShader( textureBrowser ), shader->getName() ) ) {
1337                                 glLineWidth( 2 );
1338                                 if ( textureBrowser.m_rmbSelected ) {
1339                                         glColor3f( 0,0,1 );
1340                                 }
1341                                 else {
1342                                         glColor3f( 1,0,0 );
1343                                 }
1344                                 glDisable( GL_TEXTURE_2D );
1345
1346                                 glBegin( GL_LINE_LOOP );
1347                                 glVertex2i( x - 4,y - TextureBrowser_fontHeight( textureBrowser ) + 4 );
1348                                 glVertex2i( x - 4,y - TextureBrowser_fontHeight( textureBrowser ) - nHeight - 4 );
1349                                 glVertex2i( x + 4 + nWidth,y - TextureBrowser_fontHeight( textureBrowser ) - nHeight - 4 );
1350                                 glVertex2i( x + 4 + nWidth,y - TextureBrowser_fontHeight( textureBrowser ) + 4 );
1351                                 glEnd();
1352
1353                                 glEnable( GL_TEXTURE_2D );
1354                                 glLineWidth( 1 );
1355                         }
1356                         // highlight in-use textures
1357                         else if ( !textureBrowser.m_hideUnused && shader->IsInUse() ) {
1358                         //1px with float
1359                                 float xf = (float)x;
1360                                 float yf = (float)( y - TextureBrowser_fontHeight( textureBrowser ) );
1361                                 glColor3f( 0.5,1,0.5 );
1362                                 glDisable( GL_TEXTURE_2D );
1363                                 glBegin( GL_LINE_LOOP );
1364                                 glVertex2f( xf - 3.5,yf + 3.5 );
1365                                 glVertex2f( xf - 3.5,yf - nHeight - 3.5 );
1366                                 glVertex2f( xf + 3.5 + nWidth,yf - nHeight - 3.5 );
1367                                 glVertex2f( xf + 3.5 + nWidth,yf + 3.5 );
1368                                 glEnd();
1369                                 glEnable( GL_TEXTURE_2D );
1370                         }
1371
1372                         // draw checkerboard for transparent textures
1373                         if ( g_TextureBrowser_enableAlpha )
1374                         {
1375                                 glDisable( GL_TEXTURE_2D );
1376                                 glBegin( GL_QUADS );
1377                                 int font_height = TextureBrowser_fontHeight( textureBrowser );
1378                                 for ( int i = 0; i < nHeight; i += 8 )
1379                                         for ( int j = 0; j < nWidth; j += 8 )
1380                                         {
1381                                                 unsigned char color = (i + j) / 8 % 2 ? 0x66 : 0x99;
1382                                                 glColor3ub( color, color, color );
1383                                                 int left = j;
1384                                                 int right = std::min(j+8, nWidth);
1385                                                 int top = i;
1386                                                 int bottom = std::min(i+8, nHeight);
1387                                                 glVertex2i(x + right, y - nHeight - font_height + top);
1388                                                 glVertex2i(x + left,  y - nHeight - font_height + top);
1389                                                 glVertex2i(x + left,  y - nHeight - font_height + bottom);
1390                                                 glVertex2i(x + right, y - nHeight - font_height + bottom);
1391                                         }
1392                                 glEnd();
1393                                 glEnable( GL_TEXTURE_2D );
1394                         }
1395
1396                         // Draw the texture
1397                         glBindTexture( GL_TEXTURE_2D, q->texture_number );
1398                         GlobalOpenGL_debugAssertNoErrors();
1399                         glColor3f( 1,1,1 );
1400                         glBegin( GL_QUADS );
1401                         glTexCoord2i( 0,0 );
1402                         glVertex2i( x,y - TextureBrowser_fontHeight( textureBrowser ) );
1403                         glTexCoord2i( 1,0 );
1404                         glVertex2i( x + nWidth,y - TextureBrowser_fontHeight( textureBrowser ) );
1405                         glTexCoord2i( 1,1 );
1406                         glVertex2i( x + nWidth,y - TextureBrowser_fontHeight( textureBrowser ) - nHeight );
1407                         glTexCoord2i( 0,1 );
1408                         glVertex2i( x,y - TextureBrowser_fontHeight( textureBrowser ) - nHeight );
1409                         glEnd();
1410
1411                         // draw the texture name
1412                         glDisable( GL_TEXTURE_2D );
1413                         glColor3f( 1,1,1 );
1414
1415                         glRasterPos2i( x, y - TextureBrowser_fontHeight( textureBrowser ) + 5 );
1416
1417                         // don't draw the directory name
1418                         const char* name = shader->getName();
1419                         name += strlen( name );
1420                         while ( name != shader->getName() && *( name - 1 ) != '/' && *( name - 1 ) != '\\' )
1421                                 name--;
1422
1423                         GlobalOpenGL().drawString( name );
1424                         glEnable( GL_TEXTURE_2D );
1425                 }
1426
1427                 //int totalHeight = abs(y) + last_height + TextureBrowser_fontHeight(textureBrowser) + 4;
1428         }
1429
1430
1431         // reset the current texture
1432         glBindTexture( GL_TEXTURE_2D, 0 );
1433         //qglFinish();
1434 }
1435
1436 void TextureBrowser_queueDraw( TextureBrowser& textureBrowser ){
1437         if ( textureBrowser.m_gl_widget ) {
1438                 gtk_widget_queue_draw( textureBrowser.m_gl_widget );
1439         }
1440 }
1441
1442
1443 void TextureBrowser_setScale( TextureBrowser& textureBrowser, std::size_t scale ){
1444         textureBrowser.m_textureScale = scale;
1445
1446         textureBrowser.m_heightChanged = true;
1447         textureBrowser.m_originInvalid = true;
1448         g_activeShadersChangedCallbacks();
1449
1450         TextureBrowser_queueDraw( textureBrowser );
1451 }
1452
1453 void TextureBrowser_setUniformSize( TextureBrowser& textureBrowser, std::size_t scale ){
1454         textureBrowser.m_uniformTextureSize = scale;
1455
1456         textureBrowser.m_heightChanged = true;
1457         textureBrowser.m_originInvalid = true;
1458         g_activeShadersChangedCallbacks();
1459
1460         TextureBrowser_queueDraw( textureBrowser );
1461 }
1462
1463 void TextureBrowser_setUniformMinSize( TextureBrowser& textureBrowser, std::size_t scale ){
1464         textureBrowser.m_uniformTextureMinSize = scale;
1465
1466         textureBrowser.m_heightChanged = true;
1467         textureBrowser.m_originInvalid = true;
1468         g_activeShadersChangedCallbacks();
1469
1470         TextureBrowser_queueDraw( textureBrowser );
1471 }
1472
1473 void TextureBrowser_MouseWheel( TextureBrowser& textureBrowser, bool bUp ){
1474         int originy = TextureBrowser_getOriginY( textureBrowser );
1475
1476         if ( bUp ) {
1477                 originy += int(textureBrowser.m_mouseWheelScrollIncrement);
1478         }
1479         else
1480         {
1481                 originy -= int(textureBrowser.m_mouseWheelScrollIncrement);
1482         }
1483
1484         TextureBrowser_setOriginY( textureBrowser, originy );
1485 }
1486
1487 XmlTagBuilder TagBuilder;
1488
1489 enum
1490 {
1491         TAG_COLUMN,
1492         N_COLUMNS
1493 };
1494
1495 void BuildStoreAssignedTags( ui::ListStore store, const char* shader, TextureBrowser* textureBrowser ){
1496         GtkTreeIter iter;
1497
1498         store.clear();
1499
1500         std::vector<CopiedString> assigned_tags;
1501         TagBuilder.GetShaderTags( shader, assigned_tags );
1502
1503         for ( size_t i = 0; i < assigned_tags.size(); i++ )
1504         {
1505                 store.append(TAG_COLUMN, assigned_tags[i].c_str());
1506         }
1507 }
1508
1509 void BuildStoreAvailableTags(   ui::ListStore storeAvailable,
1510                                                                 ui::ListStore storeAssigned,
1511                                                                 const std::set<CopiedString>& allTags,
1512                                                                 TextureBrowser* textureBrowser ){
1513         GtkTreeIter iterAssigned;
1514         GtkTreeIter iterAvailable;
1515         std::set<CopiedString>::const_iterator iterAll;
1516         gchar* tag_assigned;
1517
1518         storeAvailable.clear();
1519
1520         bool row = gtk_tree_model_get_iter_first(storeAssigned, &iterAssigned ) != 0;
1521
1522         if ( !row ) { // does the shader have tags assigned?
1523                 for ( iterAll = allTags.begin(); iterAll != allTags.end(); ++iterAll )
1524                 {
1525                         storeAvailable.append(TAG_COLUMN, (*iterAll).c_str());
1526                 }
1527         }
1528         else
1529         {
1530                 while ( row ) // available tags = all tags - assigned tags
1531                 {
1532                         gtk_tree_model_get(storeAssigned, &iterAssigned, TAG_COLUMN, &tag_assigned, -1 );
1533
1534                         for ( iterAll = allTags.begin(); iterAll != allTags.end(); ++iterAll )
1535                         {
1536                                 if ( strcmp( (char*)tag_assigned, ( *iterAll ).c_str() ) != 0 ) {
1537                                         storeAvailable.append(TAG_COLUMN, (*iterAll).c_str());
1538                                 }
1539                                 else
1540                                 {
1541                                         row = gtk_tree_model_iter_next(storeAssigned, &iterAssigned ) != 0;
1542
1543                                         if ( row ) {
1544                                                 gtk_tree_model_get(storeAssigned, &iterAssigned, TAG_COLUMN, &tag_assigned, -1 );
1545                                         }
1546                                 }
1547                         }
1548                 }
1549         }
1550 }
1551
1552 gboolean TextureBrowser_button_press( ui::Widget widget, GdkEventButton* event, TextureBrowser* textureBrowser ){
1553         if ( event->type == GDK_BUTTON_PRESS ) {
1554                 if ( event->button == 3 ) {
1555                         if ( textureBrowser->m_tags ) {
1556                                 textureBrowser->m_rmbSelected = true;
1557                                 TextureBrowser_Selection_MouseDown( *textureBrowser, event->state, static_cast<int>( event->x ), static_cast<int>( event->y ) );
1558
1559                                 BuildStoreAssignedTags( textureBrowser->m_assigned_store, textureBrowser->shader.c_str(), textureBrowser );
1560                                 BuildStoreAvailableTags( textureBrowser->m_available_store, textureBrowser->m_assigned_store, textureBrowser->m_all_tags, textureBrowser );
1561                                 textureBrowser->m_heightChanged = true;
1562                                 textureBrowser->m_tag_frame.show();
1563
1564                 ui::process();
1565
1566                                 TextureBrowser_Focus( *textureBrowser, textureBrowser->shader.c_str() );
1567                         }
1568                         else
1569                         {
1570                                 TextureBrowser_Tracking_MouseDown( *textureBrowser );
1571                         }
1572                 }
1573                 else if ( event->button == 1 ) {
1574                         TextureBrowser_Selection_MouseDown( *textureBrowser, event->state, static_cast<int>( event->x ), static_cast<int>( event->y ) );
1575
1576                         if ( textureBrowser->m_tags ) {
1577                                 textureBrowser->m_rmbSelected = false;
1578                                 textureBrowser->m_tag_frame.hide();
1579                         }
1580                 }
1581         }
1582         else if ( event->type == GDK_2BUTTON_PRESS ) {
1583                 #define GARUX_DISABLE_2BUTTON
1584                 #ifndef GARUX_DISABLE_2BUTTON
1585                 const char* sh = textureBrowser->shader.c_str();
1586                 char* dir = strrchr( sh, '/' );
1587                 if( dir != NULL ){
1588                         *(dir + 1) = '\0';
1589                         dir = strchr( sh, '/' );
1590                         if( dir != NULL ){
1591                                 dir++;
1592                                 if( *dir != '\0'){
1593                                         ScopeDisableScreenUpdates disableScreenUpdates( dir, "Loading Textures" );
1594                                         TextureBrowser_ShowDirectory( *textureBrowser, dir );
1595                                         TextureBrowser_queueDraw( *textureBrowser );
1596                                 }
1597                         }
1598                 }
1599                 #endif
1600         }
1601         else if ( event->type == GDK_3BUTTON_PRESS ) {
1602                 ScopeDisableScreenUpdates disableScreenUpdates( TextureBrowser_getCommonShadersDir(), "Loading Textures" );
1603                 TextureBrowser_ShowDirectory( *textureBrowser, TextureBrowser_getCommonShadersDir() );
1604                 TextureBrowser_queueDraw( *textureBrowser );
1605         }
1606         return FALSE;
1607 }
1608
1609 gboolean TextureBrowser_button_release( ui::Widget widget, GdkEventButton* event, TextureBrowser* textureBrowser ){
1610         if ( event->type == GDK_BUTTON_RELEASE ) {
1611                 if ( event->button == 3 ) {
1612                         if ( !textureBrowser->m_tags ) {
1613                                 TextureBrowser_Tracking_MouseUp( *textureBrowser );
1614                         }
1615                 }
1616         }
1617         return FALSE;
1618 }
1619
1620 gboolean TextureBrowser_motion( ui::Widget widget, GdkEventMotion *event, TextureBrowser* textureBrowser ){
1621         return FALSE;
1622 }
1623
1624 gboolean TextureBrowser_scroll( ui::Widget widget, GdkEventScroll* event, TextureBrowser* textureBrowser ){
1625         if ( event->direction == GDK_SCROLL_UP ) {
1626                 TextureBrowser_MouseWheel( *textureBrowser, true );
1627         }
1628         else if ( event->direction == GDK_SCROLL_DOWN ) {
1629                 TextureBrowser_MouseWheel( *textureBrowser, false );
1630         }
1631         return FALSE;
1632 }
1633
1634 void TextureBrowser_scrollChanged( void* data, gdouble value ){
1635         //globalOutputStream() << "vertical scroll\n";
1636         TextureBrowser_setOriginY( *reinterpret_cast<TextureBrowser*>( data ), -(int)value );
1637 }
1638
1639 static void TextureBrowser_verticalScroll(ui::Adjustment adjustment, TextureBrowser* textureBrowser ){
1640         textureBrowser->m_scrollAdjustment.value_changed( gtk_adjustment_get_value(adjustment) );
1641 }
1642
1643 void TextureBrowser_updateScroll( TextureBrowser& textureBrowser ){
1644         if ( textureBrowser.m_showTextureScrollbar ) {
1645                 int totalHeight = TextureBrowser_TotalHeight( textureBrowser );
1646
1647                 totalHeight = std::max( totalHeight, textureBrowser.height );
1648
1649         auto vadjustment = gtk_range_get_adjustment( GTK_RANGE( textureBrowser.m_texture_scroll ) );
1650
1651                 gtk_adjustment_set_value(vadjustment, -TextureBrowser_getOriginY( textureBrowser ));
1652                 gtk_adjustment_set_page_size(vadjustment, textureBrowser.height);
1653                 gtk_adjustment_set_page_increment(vadjustment, textureBrowser.height / 2);
1654                 gtk_adjustment_set_step_increment(vadjustment, 20);
1655                 gtk_adjustment_set_lower(vadjustment, 0);
1656                 gtk_adjustment_set_upper(vadjustment, totalHeight);
1657
1658                 g_signal_emit_by_name( G_OBJECT( vadjustment ), "changed" );
1659         }
1660 }
1661
1662 gboolean TextureBrowser_size_allocate( ui::Widget widget, GtkAllocation* allocation, TextureBrowser* textureBrowser ){
1663         textureBrowser->width = allocation->width;
1664         textureBrowser->height = allocation->height;
1665         TextureBrowser_heightChanged( *textureBrowser );
1666         textureBrowser->m_originInvalid = true;
1667         TextureBrowser_queueDraw( *textureBrowser );
1668         return FALSE;
1669 }
1670
1671 void TextureBrowser_redraw( TextureBrowser* textureBrowser ){
1672         if ( glwidget_make_current( textureBrowser->m_gl_widget ) != FALSE ) {
1673                 GlobalOpenGL_debugAssertNoErrors();
1674                 TextureBrowser_evaluateHeight( *textureBrowser );
1675                 Texture_Draw( *textureBrowser );
1676                 GlobalOpenGL_debugAssertNoErrors();
1677                 glwidget_swap_buffers( textureBrowser->m_gl_widget );
1678         }
1679 }
1680
1681 gboolean TextureBrowser_expose( ui::Widget widget, GdkEventExpose* event, TextureBrowser* textureBrowser ){
1682         TextureBrowser_redraw( textureBrowser );
1683         return FALSE;
1684 }
1685
1686 TextureBrowser& GlobalTextureBrowser(){
1687         static TextureBrowser textureBrowser;
1688         return textureBrowser;
1689 }
1690
1691 bool TextureBrowser_hideUnused(){
1692         return GlobalTextureBrowser().m_hideUnused;
1693 }
1694
1695 void TextureBrowser_ToggleHideUnused(){
1696         TextureBrowser &textureBrowser = GlobalTextureBrowser();
1697         if ( textureBrowser.m_hideUnused ) {
1698                 TextureBrowser_SetHideUnused( textureBrowser, false );
1699         }
1700         else
1701         {
1702                 TextureBrowser_SetHideUnused( textureBrowser, true );
1703         }
1704 }
1705
1706 const char* TextureGroups_transformDirName( const char* dirName, StringOutputStream *archiveName )
1707 {
1708         if ( TextureBrowser_showWads() ) {
1709                 archiveName->clear();
1710                 *archiveName << StringRange( path_get_filename_start( dirName ), path_get_filename_base_end( dirName ) ) \
1711                         << "." << path_get_extension( dirName );
1712                 return archiveName->c_str();
1713         }
1714         return dirName;
1715 }
1716
1717 void TextureGroups_constructTreeModel( TextureGroups groups, ui::TreeStore store ){
1718         // put the information from the old textures menu into a treeview
1719         GtkTreeIter iter, child;
1720
1721         TextureGroups::const_iterator i = groups.begin();
1722         while ( i != groups.end() )
1723         {
1724                 StringOutputStream archiveName;
1725                 StringOutputStream nextArchiveName;
1726                 const char* dirName = TextureGroups_transformDirName( ( *i ).c_str(), &archiveName );
1727
1728                 const char* firstUnderscore = strchr( dirName, '_' );
1729                 StringRange dirRoot( dirName, ( firstUnderscore == 0 ) ? dirName : firstUnderscore + 1 );
1730
1731                 TextureGroups::const_iterator next = i;
1732                 ++next;
1733
1734                 if ( firstUnderscore != 0
1735                          && next != groups.end()
1736                          && string_equal_start( TextureGroups_transformDirName( ( *next ).c_str(), &nextArchiveName ), dirRoot ) ) {
1737                         gtk_tree_store_append( store, &iter, NULL );
1738                         gtk_tree_store_set( store, &iter, 0, CopiedString( StringRange( dirName, firstUnderscore ) ).c_str(), -1 );
1739
1740                         // keep going...
1741                         while ( i != groups.end() && string_equal_start( TextureGroups_transformDirName( ( *i ).c_str(), &nextArchiveName ), dirRoot ) )
1742                         {
1743                                 gtk_tree_store_append( store, &child, &iter );
1744                                 gtk_tree_store_set( store, &child, 0, TextureGroups_transformDirName( ( *i ).c_str(), &nextArchiveName ), -1 );
1745                                 ++i;
1746                         }
1747                 }
1748                 else
1749                 {
1750                         gtk_tree_store_append( store, &iter, NULL );
1751                         gtk_tree_store_set( store, &iter, 0, dirName, -1 );
1752                         ++i;
1753                 }
1754         }
1755 }
1756
1757 TextureGroups TextureGroups_constructTreeView(){
1758         TextureGroups groups;
1759
1760         if ( TextureBrowser_showWads() ) {
1761                 GlobalFileSystem().forEachArchive( TextureGroupsAddWadCaller( groups ) );
1762         }
1763         else
1764         {
1765                 // scan texture dirs and pak files only if not restricting to shaderlist
1766                 if ( g_pGameDescription->mGameType != "doom3" && !g_TextureBrowser_shaderlistOnly ) {
1767                         GlobalFileSystem().forEachDirectory( "textures/", TextureGroupsAddDirectoryCaller( groups ) );
1768                 }
1769
1770                 GlobalShaderSystem().foreachShaderName( TextureGroupsAddShaderCaller( groups ) );
1771         }
1772
1773         return groups;
1774 }
1775
1776 void TextureBrowser_constructTreeStore(){
1777         TextureGroups groups = TextureGroups_constructTreeView();
1778         auto store = ui::TreeStore::from(gtk_tree_store_new( 1, G_TYPE_STRING ));
1779         TextureGroups_constructTreeModel( groups, store );
1780
1781         gtk_tree_view_set_model(GlobalTextureBrowser().m_treeViewTree, store);
1782
1783         g_object_unref( G_OBJECT( store ) );
1784 }
1785
1786 void TextureBrowser_constructTreeStoreTags(){
1787         TextureGroups groups;
1788         TextureBrowser &textureBrowser = GlobalTextureBrowser();
1789         auto store = ui::TreeStore::from(gtk_tree_store_new( 1, G_TYPE_STRING ));
1790         auto model = GlobalTextureBrowser().m_all_tags_list;
1791
1792         gtk_tree_view_set_model(GlobalTextureBrowser().m_treeViewTags, model );
1793
1794         g_object_unref( G_OBJECT( store ) );
1795 }
1796
1797 void TreeView_onRowActivated( ui::TreeView treeview, ui::TreePath path, ui::TreeViewColumn col, gpointer userdata ){
1798         GtkTreeIter iter;
1799
1800     auto model = gtk_tree_view_get_model(treeview );
1801
1802         if ( gtk_tree_model_get_iter( model, &iter, path ) ) {
1803                 gchar dirName[1024];
1804
1805                 gchar* buffer;
1806                 gtk_tree_model_get( model, &iter, 0, &buffer, -1 );
1807                 strcpy( dirName, buffer );
1808                 g_free( buffer );
1809
1810                 GlobalTextureBrowser().m_searchedTags = false;
1811
1812                 if ( !TextureBrowser_showWads() ) {
1813                         strcat( dirName, "/" );
1814                 }
1815
1816                 ScopeDisableScreenUpdates disableScreenUpdates( dirName, "Loading Textures" );
1817                 TextureBrowser_ShowDirectory( GlobalTextureBrowser(), dirName );
1818                 TextureBrowser_queueDraw( GlobalTextureBrowser() );
1819                 //deactivate, so SPACE and RETURN wont be broken for 2d
1820                 gtk_window_set_focus( GTK_WINDOW( gtk_widget_get_toplevel( GTK_WIDGET( treeview ) ) ), NULL );
1821         }
1822 }
1823
1824 void TextureBrowser_createTreeViewTree(){
1825         TextureBrowser &textureBrowser = GlobalTextureBrowser();
1826         gtk_tree_view_set_enable_search(textureBrowser.m_treeViewTree, FALSE );
1827
1828         gtk_tree_view_set_headers_visible(textureBrowser.m_treeViewTree, FALSE );
1829         textureBrowser.m_treeViewTree.connect( "row-activated", (GCallback) TreeView_onRowActivated, NULL );
1830
1831         auto renderer = ui::CellRendererText(ui::New);
1832         gtk_tree_view_insert_column_with_attributes(textureBrowser.m_treeViewTree, -1, "", renderer, "text", 0, NULL );
1833
1834         TextureBrowser_constructTreeStore();
1835 }
1836
1837 void TextureBrowser_addTag();
1838
1839 void TextureBrowser_renameTag();
1840
1841 void TextureBrowser_deleteTag();
1842
1843 void TextureBrowser_createContextMenu( ui::Widget treeview, GdkEventButton *event ){
1844         ui::Widget menu = ui::Menu(ui::New);
1845
1846         ui::Widget menuitem = ui::MenuItem( "Add tag" );
1847         menuitem.connect( "activate", (GCallback)TextureBrowser_addTag, treeview );
1848         gtk_menu_shell_append( GTK_MENU_SHELL( menu ), menuitem );
1849
1850         menuitem = ui::MenuItem( "Rename tag" );
1851         menuitem.connect( "activate", (GCallback)TextureBrowser_renameTag, treeview );
1852         gtk_menu_shell_append( GTK_MENU_SHELL( menu ), menuitem );
1853
1854         menuitem = ui::MenuItem( "Delete tag" );
1855         menuitem.connect( "activate", (GCallback)TextureBrowser_deleteTag, treeview );
1856         gtk_menu_shell_append( GTK_MENU_SHELL( menu ), menuitem );
1857
1858         gtk_widget_show_all( menu );
1859
1860         gtk_menu_popup( GTK_MENU( menu ), NULL, NULL, NULL, NULL,
1861                                         ( event != NULL ) ? event->button : 0,
1862                                         gdk_event_get_time( (GdkEvent*)event ) );
1863 }
1864
1865 gboolean TreeViewTags_onButtonPressed( ui::TreeView treeview, GdkEventButton *event ){
1866         if ( event->type == GDK_BUTTON_PRESS && event->button == 3 ) {
1867                 GtkTreePath *path;
1868         auto selection = gtk_tree_view_get_selection(treeview );
1869
1870                 if ( gtk_tree_view_get_path_at_pos(treeview, event->x, event->y, &path, NULL, NULL, NULL ) ) {
1871                         gtk_tree_selection_unselect_all( selection );
1872                         gtk_tree_selection_select_path( selection, path );
1873                         gtk_tree_path_free( path );
1874                 }
1875
1876                 TextureBrowser_createContextMenu( treeview, event );
1877                 return TRUE;
1878         }
1879         return FALSE;
1880 }
1881
1882 void TextureBrowser_createTreeViewTags(){
1883         TextureBrowser &textureBrowser = GlobalTextureBrowser();
1884         textureBrowser.m_treeViewTags = ui::TreeView(ui::New);
1885         gtk_tree_view_set_enable_search(textureBrowser.m_treeViewTags, FALSE );
1886
1887         textureBrowser.m_treeViewTags.connect( "button-press-event", (GCallback)TreeViewTags_onButtonPressed, NULL );
1888
1889         gtk_tree_view_set_headers_visible(textureBrowser.m_treeViewTags, FALSE );
1890
1891         auto renderer = ui::CellRendererText(ui::New);
1892         gtk_tree_view_insert_column_with_attributes(textureBrowser.m_treeViewTags, -1, "", renderer, "text", 0, NULL );
1893
1894         TextureBrowser_constructTreeStoreTags();
1895 }
1896
1897 ui::MenuItem TextureBrowser_constructViewMenu( ui::Menu menu ){
1898         TextureBrowser &textureBrowser = GlobalTextureBrowser();
1899         ui::MenuItem textures_menu_item = ui::MenuItem(new_sub_menu_item_with_mnemonic( "_View" ));
1900
1901         if ( g_Layout_enableDetachableMenus.m_value ) {
1902                 menu_tearoff( menu );
1903         }
1904
1905         create_check_menu_item_with_mnemonic( menu, "Hide _Unused", "ShowInUse" );
1906         if ( string_empty( g_pGameDescription->getKeyValue( "show_wads" ) ) ) {
1907                 create_check_menu_item_with_mnemonic( menu, "Hide Image Missing", "FilterMissing" );
1908         }
1909
1910         // hide notex and shadernotex on texture browser: no one wants to apply them
1911         create_check_menu_item_with_mnemonic( menu, "Hide Fallback", "FilterFallback" );
1912
1913         menu_separator( menu );
1914
1915
1916         // we always want to show shaders but don't want a "Show Shaders" menu for doom3 and .wad file games
1917         if ( g_pGameDescription->mGameType == "doom3" || TextureBrowser_showWads() ) {
1918                 textureBrowser.m_showShaders = true;
1919         }
1920         else
1921         {
1922                 create_check_menu_item_with_mnemonic( menu, "Show shaders", "ToggleShowShaders" );
1923                 create_check_menu_item_with_mnemonic( menu, "Show textures", "ToggleShowTextures" );
1924                 menu_separator( menu );
1925         }
1926
1927         if ( textureBrowser.m_tags ) {
1928                 create_menu_item_with_mnemonic( menu, "Show Untagged", "ShowUntagged" );
1929         }
1930         if ( g_pGameDescription->mGameType != "doom3" && string_empty( g_pGameDescription->getKeyValue( "show_wads" ) ) ) {
1931                 create_check_menu_item_with_mnemonic( menu, "ShaderList Only", "ToggleShowShaderlistOnly" );
1932         }
1933
1934         menu_separator( menu );
1935         create_check_menu_item_with_mnemonic( menu, "Fixed Size", "FixedSize" );
1936         create_check_menu_item_with_mnemonic( menu, "Transparency", "EnableAlpha" );
1937
1938         if ( string_empty( g_pGameDescription->getKeyValue( "show_wads" ) ) ) {
1939                 menu_separator( menu );
1940                 textureBrowser.m_shader_info_item = ui::Widget(create_menu_item_with_mnemonic( menu, "Shader Info", "ShaderInfo"  ));
1941                 gtk_widget_set_sensitive( textureBrowser.m_shader_info_item, FALSE );
1942         }
1943
1944
1945         return textures_menu_item;
1946 }
1947
1948 void Popup_View_Menu( GtkWidget *widget, GtkMenu *menu ){
1949         gtk_menu_popup( menu, NULL, NULL, NULL, NULL, 1, gtk_get_current_event_time() );
1950 }
1951
1952 ui::MenuItem TextureBrowser_constructToolsMenu( ui::Menu menu ){
1953         ui::MenuItem textures_menu_item = ui::MenuItem(new_sub_menu_item_with_mnemonic( "_Tools" ));
1954
1955         if ( g_Layout_enableDetachableMenus.m_value ) {
1956                 menu_tearoff( menu );
1957         }
1958
1959         create_menu_item_with_mnemonic( menu, "Flush & Reload Shaders", "RefreshShaders" );
1960         create_menu_item_with_mnemonic( menu, "Find / Replace...", "FindReplaceTextures" );
1961
1962         return textures_menu_item;
1963 }
1964
1965 ui::MenuItem TextureBrowser_constructTagsMenu( ui::Menu menu ){
1966         ui::MenuItem textures_menu_item = ui::MenuItem(new_sub_menu_item_with_mnemonic( "T_ags" ));
1967
1968         if ( g_Layout_enableDetachableMenus.m_value ) {
1969                 menu_tearoff( menu );
1970         }
1971
1972         create_menu_item_with_mnemonic( menu, "Add tag", "AddTag" );
1973         create_menu_item_with_mnemonic( menu, "Rename tag", "RenameTag" );
1974         create_menu_item_with_mnemonic( menu, "Delete tag", "DeleteTag" );
1975         menu_separator( menu );
1976         create_menu_item_with_mnemonic( menu, "Copy tags from selected", "CopyTag" );
1977         create_menu_item_with_mnemonic( menu, "Paste tags to selected", "PasteTag" );
1978
1979         return textures_menu_item;
1980 }
1981
1982 gboolean TextureBrowser_tagMoveHelper( ui::TreeModel model, ui::TreePath path, GtkTreeIter* iter, GSList** selected ){
1983         g_assert( selected != NULL );
1984
1985     auto rowref = gtk_tree_row_reference_new( model, path );
1986         *selected = g_slist_append( *selected, rowref );
1987
1988         return FALSE;
1989 }
1990
1991 void TextureBrowser_assignTags(){
1992         GSList* selected = NULL;
1993         GSList* node;
1994         gchar* tag_assigned;
1995         TextureBrowser &textureBrowser = GlobalTextureBrowser();
1996
1997         auto selection = gtk_tree_view_get_selection(textureBrowser.m_available_tree );
1998
1999         gtk_tree_selection_selected_foreach( selection, (GtkTreeSelectionForeachFunc)TextureBrowser_tagMoveHelper, &selected );
2000
2001         if ( selected != NULL ) {
2002                 for ( node = selected; node != NULL; node = node->next )
2003                 {
2004             auto path = gtk_tree_row_reference_get_path( (GtkTreeRowReference*)node->data );
2005
2006                         if ( path ) {
2007                                 GtkTreeIter iter;
2008
2009                                 if ( gtk_tree_model_get_iter(textureBrowser.m_available_store, &iter, path ) ) {
2010                                         gtk_tree_model_get(textureBrowser.m_available_store, &iter, TAG_COLUMN, &tag_assigned, -1 );
2011                                         if ( !TagBuilder.CheckShaderTag( textureBrowser.shader.c_str() ) ) {
2012                                                 // create a custom shader/texture entry
2013                                                 IShader* ishader = QERApp_Shader_ForName( textureBrowser.shader.c_str() );
2014                                                 CopiedString filename = ishader->getShaderFileName();
2015
2016                                                 if ( filename.empty() ) {
2017                                                         // it's a texture
2018                                                         TagBuilder.AddShaderNode( textureBrowser.shader.c_str(), CUSTOM, TEXTURE );
2019                                                 }
2020                                                 else {
2021                                                         // it's a shader
2022                                                         TagBuilder.AddShaderNode( textureBrowser.shader.c_str(), CUSTOM, SHADER );
2023                                                 }
2024                                                 ishader->DecRef();
2025                                         }
2026                                         TagBuilder.AddShaderTag( textureBrowser.shader.c_str(), (char*)tag_assigned, TAG );
2027
2028                                         gtk_list_store_remove( textureBrowser.m_available_store, &iter );
2029                                         textureBrowser.m_assigned_store.append(TAG_COLUMN, tag_assigned);
2030                                 }
2031                         }
2032                 }
2033
2034                 g_slist_foreach( selected, (GFunc)gtk_tree_row_reference_free, NULL );
2035
2036                 // Save changes
2037                 TagBuilder.SaveXmlDoc();
2038         }
2039         g_slist_free( selected );
2040 }
2041
2042 void TextureBrowser_removeTags(){
2043         GSList* selected = NULL;
2044         GSList* node;
2045         gchar* tag;
2046         TextureBrowser &textureBrowser = GlobalTextureBrowser();
2047
2048         auto selection = gtk_tree_view_get_selection(textureBrowser.m_assigned_tree );
2049
2050         gtk_tree_selection_selected_foreach( selection, (GtkTreeSelectionForeachFunc)TextureBrowser_tagMoveHelper, &selected );
2051
2052         if ( selected != NULL ) {
2053                 for ( node = selected; node != NULL; node = node->next )
2054                 {
2055             auto path = gtk_tree_row_reference_get_path( (GtkTreeRowReference*)node->data );
2056
2057                         if ( path ) {
2058                                 GtkTreeIter iter;
2059
2060                                 if ( gtk_tree_model_get_iter(textureBrowser.m_assigned_store, &iter, path ) ) {
2061                                         gtk_tree_model_get(textureBrowser.m_assigned_store, &iter, TAG_COLUMN, &tag, -1 );
2062                                         TagBuilder.DeleteShaderTag( textureBrowser.shader.c_str(), tag );
2063                                         gtk_list_store_remove( textureBrowser.m_assigned_store, &iter );
2064                                 }
2065                         }
2066                 }
2067
2068                 g_slist_foreach( selected, (GFunc)gtk_tree_row_reference_free, NULL );
2069
2070                 // Update the "available tags list"
2071                 BuildStoreAvailableTags( textureBrowser.m_available_store, textureBrowser.m_assigned_store, textureBrowser.m_all_tags, &textureBrowser );
2072
2073                 // Save changes
2074                 TagBuilder.SaveXmlDoc();
2075         }
2076         g_slist_free( selected );
2077 }
2078
2079 void TextureBrowser_buildTagList(){
2080         TextureBrowser &textureBrowser = GlobalTextureBrowser();
2081         textureBrowser.m_all_tags_list.clear();
2082
2083         std::set<CopiedString>::iterator iter;
2084
2085         for ( iter = textureBrowser.m_all_tags.begin(); iter != textureBrowser.m_all_tags.end(); ++iter )
2086         {
2087                 textureBrowser.m_all_tags_list.append(TAG_COLUMN, (*iter).c_str());
2088         }
2089 }
2090
2091 void TextureBrowser_searchTags(){
2092         GSList* selected = NULL;
2093         GSList* node;
2094         gchar* tag;
2095         char buffer[256];
2096         char tags_searched[256];
2097         TextureBrowser &textureBrowser = GlobalTextureBrowser();
2098
2099         auto selection = gtk_tree_view_get_selection(textureBrowser.m_treeViewTags );
2100
2101         gtk_tree_selection_selected_foreach( selection, (GtkTreeSelectionForeachFunc)TextureBrowser_tagMoveHelper, &selected );
2102
2103         if ( selected != NULL ) {
2104                 strcpy( buffer, "/root/*/*[tag='" );
2105                 strcpy( tags_searched, "[TAGS] " );
2106
2107                 for ( node = selected; node != NULL; node = node->next )
2108                 {
2109             auto path = gtk_tree_row_reference_get_path( (GtkTreeRowReference*)node->data );
2110
2111                         if ( path ) {
2112                                 GtkTreeIter iter;
2113
2114                                 if ( gtk_tree_model_get_iter(textureBrowser.m_all_tags_list, &iter, path ) ) {
2115                                         gtk_tree_model_get(textureBrowser.m_all_tags_list, &iter, TAG_COLUMN, &tag, -1 );
2116
2117                                         strcat( buffer, tag );
2118                                         strcat( tags_searched, tag );
2119                                         if ( node != g_slist_last( node ) ) {
2120                                                 strcat( buffer, "' and tag='" );
2121                                                 strcat( tags_searched, ", " );
2122                                         }
2123                                 }
2124                         }
2125                 }
2126
2127                 strcat( buffer, "']" );
2128
2129                 g_slist_foreach( selected, (GFunc)gtk_tree_row_reference_free, NULL );
2130
2131                 textureBrowser.m_found_shaders.clear(); // delete old list
2132                 TagBuilder.TagSearch( buffer, textureBrowser.m_found_shaders );
2133
2134                 if ( !textureBrowser.m_found_shaders.empty() ) { // found something
2135                         size_t shaders_found = textureBrowser.m_found_shaders.size();
2136
2137                         globalOutputStream() << "Found " << (unsigned int)shaders_found << " textures and shaders with " << tags_searched << "\n";
2138                         ScopeDisableScreenUpdates disableScreenUpdates( "Searching...", "Loading Textures" );
2139
2140                         std::set<CopiedString>::iterator iter;
2141
2142                         for ( iter = textureBrowser.m_found_shaders.begin(); iter != textureBrowser.m_found_shaders.end(); iter++ )
2143                         {
2144                                 std::string path = ( *iter ).c_str();
2145                                 size_t pos = path.find_last_of( "/", path.size() );
2146                                 std::string name = path.substr( pos + 1, path.size() );
2147                                 path = path.substr( 0, pos + 1 );
2148                                 TextureDirectory_loadTexture( path.c_str(), name.c_str() );
2149                         }
2150                 }
2151                 textureBrowser.m_searchedTags = true;
2152                 g_TextureBrowser_currentDirectory = tags_searched;
2153
2154                 textureBrowser.m_nTotalHeight = 0;
2155                 TextureBrowser_setOriginY( textureBrowser, 0 );
2156                 TextureBrowser_heightChanged( textureBrowser );
2157                 TextureBrowser_updateTitle();
2158         }
2159         g_slist_free( selected );
2160 }
2161
2162 void TextureBrowser_toggleSearchButton(){
2163         TextureBrowser &textureBrowser = GlobalTextureBrowser();
2164         gint page = gtk_notebook_get_current_page( GTK_NOTEBOOK( textureBrowser.m_tag_notebook ) );
2165
2166         if ( page == 0 ) { // tag page
2167                 gtk_widget_show_all( textureBrowser.m_search_button );
2168         }
2169         else {
2170                 textureBrowser.m_search_button.hide();
2171         }
2172 }
2173
2174 void TextureBrowser_constructTagNotebook(){
2175         TextureBrowser &textureBrowser = GlobalTextureBrowser();
2176         textureBrowser.m_tag_notebook = ui::Widget::from(gtk_notebook_new());
2177         ui::Widget labelTags = ui::Label( "Tags" );
2178         ui::Widget labelTextures = ui::Label( "Textures" );
2179
2180         gtk_notebook_append_page( GTK_NOTEBOOK( textureBrowser.m_tag_notebook ), textureBrowser.m_scr_win_tree, labelTextures );
2181         gtk_notebook_append_page( GTK_NOTEBOOK( textureBrowser.m_tag_notebook ), textureBrowser.m_scr_win_tags, labelTags );
2182
2183         textureBrowser.m_tag_notebook.connect( "switch-page", G_CALLBACK( TextureBrowser_toggleSearchButton ), NULL );
2184
2185         gtk_widget_show_all( textureBrowser.m_tag_notebook );
2186 }
2187
2188 void TextureBrowser_constructSearchButton(){
2189         auto image = ui::Widget::from(gtk_image_new_from_stock( GTK_STOCK_FIND, GTK_ICON_SIZE_SMALL_TOOLBAR ));
2190         TextureBrowser &textureBrowser = GlobalTextureBrowser();
2191         textureBrowser.m_search_button = ui::Button(ui::New);
2192         textureBrowser.m_search_button.connect( "clicked", G_CALLBACK( TextureBrowser_searchTags ), NULL );
2193         gtk_widget_set_tooltip_text(textureBrowser.m_search_button, "Search with selected tags");
2194         textureBrowser.m_search_button.add(image);
2195 }
2196
2197 void TextureBrowser_checkTagFile(){
2198         const char SHADERTAG_FILE[] = "shadertags.xml";
2199         CopiedString default_filename, rc_filename;
2200         StringOutputStream stream( 256 );
2201         TextureBrowser &textureBrowser = GlobalTextureBrowser();
2202
2203         stream << LocalRcPath_get();
2204         stream << SHADERTAG_FILE;
2205         rc_filename = stream.c_str();
2206
2207         if ( file_exists( rc_filename.c_str() ) ) {
2208                 textureBrowser.m_tags = TagBuilder.OpenXmlDoc( rc_filename.c_str() );
2209
2210                 if ( textureBrowser.m_tags ) {
2211                         globalOutputStream() << "Loading tag file " << rc_filename.c_str() << ".\n";
2212                 }
2213         }
2214         else
2215         {
2216                 // load default tagfile
2217                 stream.clear();
2218                 stream << g_pGameDescription->mGameToolsPath.c_str();
2219                 stream << SHADERTAG_FILE;
2220                 default_filename = stream.c_str();
2221
2222                 if ( file_exists( default_filename.c_str() ) ) {
2223                         textureBrowser.m_tags = TagBuilder.OpenXmlDoc( default_filename.c_str(), rc_filename.c_str() );
2224
2225                         if ( textureBrowser.m_tags ) {
2226                                 globalOutputStream() << "Loading default tag file " << default_filename.c_str() << ".\n";
2227                         }
2228                 }
2229                 else
2230                 {
2231                         globalErrorStream() << "Unable to find default tag file " << default_filename.c_str() << ". No tag support.\n";
2232                 }
2233         }
2234 }
2235
2236 void TextureBrowser_SetNotex(){
2237         IShader* notex = QERApp_Shader_ForName( DEFAULT_NOTEX_NAME );
2238         IShader* shadernotex = QERApp_Shader_ForName( DEFAULT_SHADERNOTEX_NAME );
2239
2240         g_notex = notex->getTexture()->name;
2241
2242         g_shadernotex = shadernotex->getTexture()->name;
2243
2244         notex->DecRef();
2245         shadernotex->DecRef();
2246 }
2247
2248 static bool isGLWidgetConstructed = false;
2249 static bool isWindowConstructed = false;
2250
2251 void TextureBrowser_constructGLWidget(){
2252         TextureBrowser &textureBrowser = GlobalTextureBrowser();
2253         textureBrowser.m_gl_widget = glwidget_new( FALSE );
2254         g_object_ref( textureBrowser.m_gl_widget._handle );
2255
2256         gtk_widget_set_events( textureBrowser.m_gl_widget, GDK_DESTROY | GDK_EXPOSURE_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK | GDK_POINTER_MOTION_MASK | GDK_SCROLL_MASK );
2257         gtk_widget_set_can_focus( textureBrowser.m_gl_widget, true );
2258
2259         textureBrowser.m_sizeHandler = textureBrowser.m_gl_widget.connect( "size_allocate", G_CALLBACK( TextureBrowser_size_allocate ), &textureBrowser );
2260         textureBrowser.m_exposeHandler = textureBrowser.m_gl_widget.on_render( G_CALLBACK( TextureBrowser_expose ), &textureBrowser );
2261
2262         textureBrowser.m_gl_widget.connect( "button_press_event", G_CALLBACK( TextureBrowser_button_press ), &textureBrowser );
2263         textureBrowser.m_gl_widget.connect( "button_release_event", G_CALLBACK( TextureBrowser_button_release ), &textureBrowser );
2264         textureBrowser.m_gl_widget.connect( "motion_notify_event", G_CALLBACK( TextureBrowser_motion ), &textureBrowser );
2265         textureBrowser.m_gl_widget.connect( "scroll_event", G_CALLBACK( TextureBrowser_scroll ), &textureBrowser );
2266
2267 #ifdef WORKAROUND_MACOS_GTK2_GLWIDGET
2268         textureBrowser.m_hframe.pack_start( textureBrowser.m_gl_widget, TRUE, TRUE, 0 );
2269 #else // !WORKAROUND_MACOS_GTK2_GLWIDGET
2270         textureBrowser.m_frame.pack_start( textureBrowser.m_gl_widget, TRUE, TRUE, 0 );
2271 #endif // !WORKAROUND_MACOS_GTK2_GLWIDGET
2272
2273         textureBrowser.m_gl_widget.show();
2274
2275         isGLWidgetConstructed = true;
2276 }
2277
2278 ui::Widget TextureBrowser_constructWindow( ui::Window toplevel ){
2279         // The gl_widget and the tag assignment frame should be packed into a GtkVPaned with the slider
2280         // position stored in local.pref. gtk_paned_get_position() and gtk_paned_set_position() don't
2281         // seem to work in gtk 2.4 and the arrow buttons don't handle GTK_FILL, so here's another thing
2282         // for the "once-the-gtk-libs-are-updated-TODO-list" :x
2283         TextureBrowser &textureBrowser = GlobalTextureBrowser();
2284
2285         TextureBrowser_checkTagFile();
2286         TextureBrowser_SetNotex();
2287
2288         GlobalShaderSystem().setActiveShadersChangedNotify( ReferenceCaller<TextureBrowser, void(), TextureBrowser_activeShadersChanged>( textureBrowser ) );
2289
2290         textureBrowser.m_parent = toplevel;
2291
2292         auto table = ui::Table(3, 3, FALSE);
2293         auto vbox = ui::VBox(FALSE, 0);
2294         table.attach(vbox, {0, 1, 1, 3}, {GTK_FILL, GTK_FILL});
2295         vbox.show();
2296
2297         // ui::Widget menu_bar{ui::null};
2298         auto toolbar = ui::Toolbar::from( gtk_toolbar_new() );
2299
2300         { // menu bar
2301                 // menu_bar = ui::Widget::from(gtk_menu_bar_new());
2302                 auto menu_view = ui::Menu(ui::New);
2303                 // auto view_item = TextureBrowser_constructViewMenu( menu_view );
2304                 TextureBrowser_constructViewMenu( menu_view );
2305                 gtk_menu_set_title( menu_view, "View" );
2306                 // gtk_menu_item_set_submenu( GTK_MENU_ITEM( view_item ), menu_view );
2307                 // gtk_menu_shell_append( GTK_MENU_SHELL( menu_bar ), view_item );
2308
2309                 //gtk_table_attach( GTK_TABLE( table ), GTK_WIDGET( toolbar ), 0, 1, 0, 1, GTK_FILL, GTK_FILL, 0, 0 );
2310                 gtk_box_pack_start( GTK_BOX( vbox ), GTK_WIDGET( toolbar ), FALSE, FALSE, 0 );
2311
2312                 //view menu button
2313                 {
2314                         auto button = toolbar_append_button( toolbar, "View", "texbro_view.png" );
2315                         button.dimensions( 22, 22 );
2316                         button.connect( "clicked", G_CALLBACK( Popup_View_Menu ), menu_view );
2317
2318                         //to show detached menu over floating tex bro
2319                         gtk_menu_attach_to_widget( GTK_MENU( menu_view ), GTK_WIDGET( button ), NULL );
2320                 }
2321                 {
2322                         auto button = toolbar_append_button( toolbar, "Find / Replace...", "texbro_gtk-find-and-replace.png", "FindReplaceTextures" );
2323                         button.dimensions( 22, 22 );
2324                 }
2325                 {
2326                         auto button = toolbar_append_button( toolbar, "Flush & Reload Shaders", "texbro_refresh.png", "RefreshShaders" );
2327                         button.dimensions( 22, 22 );
2328                 }
2329                 toolbar.show();
2330
2331 /*
2332                 auto menu_tools = ui::Menu(ui::New);
2333                 auto tools_item = TextureBrowser_constructToolsMenu( menu_tools );
2334                 gtk_menu_item_set_submenu( GTK_MENU_ITEM( tools_item ), menu_tools );
2335                 gtk_menu_shell_append( GTK_MENU_SHELL( menu_bar ), tools_item );
2336 */
2337                 // table.attach(menu_bar, {0, 3, 0, 1}, {GTK_FILL, GTK_SHRINK});
2338                 // menu_bar.show();
2339         }
2340         { // Texture TreeView
2341                 textureBrowser.m_scr_win_tree = ui::ScrolledWindow(ui::New);
2342                 gtk_container_set_border_width( GTK_CONTAINER( textureBrowser.m_scr_win_tree ), 0 );
2343
2344                 // vertical only scrolling for treeview
2345                 gtk_scrolled_window_set_policy( GTK_SCROLLED_WINDOW( textureBrowser.m_scr_win_tree ), GTK_POLICY_NEVER, GTK_POLICY_ALWAYS );
2346
2347                 textureBrowser.m_scr_win_tree.show();
2348
2349                 TextureBrowser_createTreeViewTree();
2350
2351                 gtk_scrolled_window_add_with_viewport( GTK_SCROLLED_WINDOW( textureBrowser.m_scr_win_tree ), textureBrowser.m_treeViewTree  );
2352                 textureBrowser.m_treeViewTree.show();
2353         }
2354         { // gl_widget scrollbar
2355                 auto w = ui::Widget::from(gtk_vscrollbar_new( ui::Adjustment( 0,0,0,1,1,0 ) ));
2356                 table.attach(w, {2, 3, 1, 2}, {GTK_SHRINK, GTK_FILL});
2357                 w.show();
2358                 textureBrowser.m_texture_scroll = w;
2359
2360                 auto vadjustment = ui::Adjustment::from(gtk_range_get_adjustment( GTK_RANGE( textureBrowser.m_texture_scroll ) ));
2361                 vadjustment.connect( "value_changed", G_CALLBACK( TextureBrowser_verticalScroll ), &textureBrowser );
2362
2363                 textureBrowser.m_texture_scroll.visible(textureBrowser.m_showTextureScrollbar);
2364         }
2365         { // gl_widget
2366 #ifdef WORKAROUND_MACOS_GTK2_GLWIDGET
2367                 textureBrowser.m_vframe = ui::VBox( FALSE, 0 );
2368                 table.attach(textureBrowser.m_vframe, {1, 2, 1, 2});
2369
2370                 textureBrowser.m_vfiller = ui::VBox( FALSE, 0 );
2371                 textureBrowser.m_vframe.pack_start( textureBrowser.m_vfiller, FALSE, FALSE, 0 );
2372
2373                 textureBrowser.m_hframe = ui::HBox( FALSE, 0 );
2374                 textureBrowser.m_vframe.pack_start( textureBrowser.m_hframe, TRUE, TRUE, 0 );
2375
2376                 textureBrowser.m_hfiller = ui::HBox( FALSE, 0 );
2377                 textureBrowser.m_hframe.pack_start( textureBrowser.m_hfiller, FALSE, FALSE, 0 );
2378
2379                 textureBrowser.m_vframe.show();
2380                 textureBrowser.m_vfiller.show();
2381                 textureBrowser.m_hframe.show(),
2382                 textureBrowser.m_hfiller.show();
2383 #else // !WORKAROUND_MACOS_GTK2_GLWIDGET
2384                 textureBrowser.m_frame = ui::VBox( FALSE, 0 );
2385                 table.attach(textureBrowser.m_frame, {1, 2, 1, 2});
2386                 textureBrowser.m_frame.show();
2387 #endif // !WORKAROUND_MACOS_GTK2_GLWIDGET
2388
2389                 TextureBrowser_constructGLWidget();
2390         }
2391
2392         // tag stuff
2393         if ( textureBrowser.m_tags ) {
2394                 { // fill tag GtkListStore
2395                         textureBrowser.m_all_tags_list = ui::ListStore::from(gtk_list_store_new( N_COLUMNS, G_TYPE_STRING ));
2396             auto sortable = GTK_TREE_SORTABLE( textureBrowser.m_all_tags_list );
2397                         gtk_tree_sortable_set_sort_column_id( sortable, TAG_COLUMN, GTK_SORT_ASCENDING );
2398
2399                         TagBuilder.GetAllTags( textureBrowser.m_all_tags );
2400                         TextureBrowser_buildTagList();
2401                 }
2402                 { // tag menu bar
2403                         auto menu_tags = ui::Menu(ui::New);
2404                         // auto tags_item = TextureBrowser_constructTagsMenu( menu_tags );
2405                         TextureBrowser_constructTagsMenu( menu_tags );
2406                         // gtk_menu_item_set_submenu( GTK_MENU_ITEM( tags_item ), menu_tags );
2407                         // gtk_menu_shell_append( GTK_MENU_SHELL( menu_bar ), tags_item );
2408
2409                         auto button = toolbar_append_button( toolbar, "Tags", "texbro_tags.png" );
2410                         button.dimensions( 22, 22 );
2411                         button.connect( "clicked", G_CALLBACK( Popup_View_Menu ), menu_tags );
2412                 }
2413                 { // Tag TreeView
2414                         textureBrowser.m_scr_win_tags = ui::ScrolledWindow(ui::New);
2415                         gtk_container_set_border_width( GTK_CONTAINER( textureBrowser.m_scr_win_tags ), 0 );
2416
2417                         // vertical only scrolling for treeview
2418                         gtk_scrolled_window_set_policy( GTK_SCROLLED_WINDOW( textureBrowser.m_scr_win_tags ), GTK_POLICY_NEVER, GTK_POLICY_ALWAYS );
2419
2420                         TextureBrowser_createTreeViewTags();
2421
2422             auto selection = gtk_tree_view_get_selection(textureBrowser.m_treeViewTags );
2423                         gtk_tree_selection_set_mode( selection, GTK_SELECTION_MULTIPLE );
2424
2425                         gtk_scrolled_window_add_with_viewport( GTK_SCROLLED_WINDOW( textureBrowser.m_scr_win_tags ), textureBrowser.m_treeViewTags  );
2426                         textureBrowser.m_treeViewTags.show();
2427                 }
2428                 { // Texture/Tag notebook
2429                         TextureBrowser_constructTagNotebook();
2430                         vbox.pack_start( textureBrowser.m_tag_notebook, TRUE, TRUE, 0 );
2431                 }
2432                 { // Tag search button
2433                         TextureBrowser_constructSearchButton();
2434                         vbox.pack_end(textureBrowser.m_search_button, FALSE, FALSE, 0);
2435                 }
2436                 auto frame_table = ui::Table(3, 3, FALSE);
2437                 { // Tag frame
2438
2439                         textureBrowser.m_tag_frame = ui::Frame( "Tag assignment" );
2440                         gtk_frame_set_label_align( GTK_FRAME( textureBrowser.m_tag_frame ), 0.5, 0.5 );
2441                         gtk_frame_set_shadow_type( GTK_FRAME( textureBrowser.m_tag_frame ), GTK_SHADOW_NONE );
2442
2443                         table.attach(textureBrowser.m_tag_frame, {1, 3, 2, 3}, {GTK_FILL, GTK_SHRINK});
2444
2445                         frame_table.show();
2446
2447                         textureBrowser.m_tag_frame.add(frame_table);
2448                 }
2449                 { // assigned tag list
2450                         ui::Widget scrolled_win = ui::ScrolledWindow(ui::New);
2451                         gtk_container_set_border_width( GTK_CONTAINER( scrolled_win ), 0 );
2452                         gtk_scrolled_window_set_policy( GTK_SCROLLED_WINDOW( scrolled_win ), GTK_POLICY_NEVER, GTK_POLICY_ALWAYS );
2453
2454                         textureBrowser.m_assigned_store = ui::ListStore::from(gtk_list_store_new( N_COLUMNS, G_TYPE_STRING ));
2455
2456             auto sortable = GTK_TREE_SORTABLE( textureBrowser.m_assigned_store );
2457                         gtk_tree_sortable_set_sort_column_id( sortable, TAG_COLUMN, GTK_SORT_ASCENDING );
2458
2459                         auto renderer = ui::CellRendererText(ui::New);
2460
2461                         textureBrowser.m_assigned_tree = ui::TreeView(ui::TreeModel::from(textureBrowser.m_assigned_store._handle));
2462                         textureBrowser.m_assigned_store.unref();
2463                         textureBrowser.m_assigned_tree.connect( "row-activated", (GCallback) TextureBrowser_removeTags, NULL );
2464                         gtk_tree_view_set_headers_visible(textureBrowser.m_assigned_tree, FALSE );
2465
2466             auto selection = gtk_tree_view_get_selection(textureBrowser.m_assigned_tree );
2467                         gtk_tree_selection_set_mode( selection, GTK_SELECTION_MULTIPLE );
2468
2469             auto column = ui::TreeViewColumn( "", renderer, {{"text", TAG_COLUMN}} );
2470                         gtk_tree_view_append_column(textureBrowser.m_assigned_tree, column );
2471                         textureBrowser.m_assigned_tree.show();
2472
2473                         scrolled_win.show();
2474                         gtk_scrolled_window_add_with_viewport( GTK_SCROLLED_WINDOW( scrolled_win ), textureBrowser.m_assigned_tree  );
2475
2476                         frame_table.attach(scrolled_win, {0, 1, 1, 3}, {GTK_FILL, GTK_FILL});
2477                 }
2478                 { // available tag list
2479                         ui::Widget scrolled_win = ui::ScrolledWindow(ui::New);
2480                         gtk_container_set_border_width( GTK_CONTAINER( scrolled_win ), 0 );
2481                         gtk_scrolled_window_set_policy( GTK_SCROLLED_WINDOW( scrolled_win ), GTK_POLICY_NEVER, GTK_POLICY_ALWAYS );
2482
2483                         textureBrowser.m_available_store = ui::ListStore::from(gtk_list_store_new( N_COLUMNS, G_TYPE_STRING ));
2484             auto sortable = GTK_TREE_SORTABLE( textureBrowser.m_available_store );
2485                         gtk_tree_sortable_set_sort_column_id( sortable, TAG_COLUMN, GTK_SORT_ASCENDING );
2486
2487                         auto renderer = ui::CellRendererText(ui::New);
2488
2489                         textureBrowser.m_available_tree = ui::TreeView(ui::TreeModel::from(textureBrowser.m_available_store._handle));
2490                         textureBrowser.m_available_store.unref();
2491                         textureBrowser.m_available_tree.connect( "row-activated", (GCallback) TextureBrowser_assignTags, NULL );
2492                         gtk_tree_view_set_headers_visible(textureBrowser.m_available_tree, FALSE );
2493
2494             auto selection = gtk_tree_view_get_selection(textureBrowser.m_available_tree );
2495                         gtk_tree_selection_set_mode( selection, GTK_SELECTION_MULTIPLE );
2496
2497             auto column = ui::TreeViewColumn( "", renderer, {{"text", TAG_COLUMN}} );
2498                         gtk_tree_view_append_column(textureBrowser.m_available_tree, column );
2499                         textureBrowser.m_available_tree.show();
2500
2501                         scrolled_win.show();
2502                         gtk_scrolled_window_add_with_viewport( GTK_SCROLLED_WINDOW( scrolled_win ), textureBrowser.m_available_tree  );
2503
2504                         frame_table.attach(scrolled_win, {2, 3, 1, 3}, {GTK_FILL, GTK_FILL});
2505                 }
2506                 { // tag arrow buttons
2507                         auto m_btn_left = ui::Button(ui::New);
2508                         auto m_btn_right = ui::Button(ui::New);
2509                         auto m_arrow_left = ui::Widget::from(gtk_arrow_new( GTK_ARROW_LEFT, GTK_SHADOW_OUT ));
2510                         auto m_arrow_right = ui::Widget::from(gtk_arrow_new( GTK_ARROW_RIGHT, GTK_SHADOW_OUT ));
2511                         m_btn_left.add(m_arrow_left);
2512                         m_btn_right.add(m_arrow_right);
2513
2514                         // workaround. the size of the tag frame depends of the requested size of the arrow buttons.
2515                         m_arrow_left.dimensions(-1, 68);
2516                         m_arrow_right.dimensions(-1, 68);
2517
2518                         frame_table.attach(m_btn_left, {1, 2, 1, 2}, {GTK_SHRINK, GTK_EXPAND});
2519                         frame_table.attach(m_btn_right, {1, 2, 2, 3}, {GTK_SHRINK, GTK_EXPAND});
2520
2521                         m_btn_left.connect( "clicked", G_CALLBACK( TextureBrowser_assignTags ), NULL );
2522                         m_btn_right.connect( "clicked", G_CALLBACK( TextureBrowser_removeTags ), NULL );
2523
2524                         m_btn_left.show();
2525                         m_btn_right.show();
2526                         m_arrow_left.show();
2527                         m_arrow_right.show();
2528                 }
2529                 { // tag fram labels
2530                         ui::Widget m_lbl_assigned = ui::Label( "Assigned" );
2531                         ui::Widget m_lbl_unassigned = ui::Label( "Available" );
2532
2533                         frame_table.attach(m_lbl_assigned, {0, 1, 0, 1}, {GTK_EXPAND, GTK_SHRINK});
2534                         frame_table.attach(m_lbl_unassigned, {2, 3, 0, 1}, {GTK_EXPAND, GTK_SHRINK});
2535
2536                         m_lbl_assigned.show();
2537                         m_lbl_unassigned.show();
2538                 }
2539         }
2540         else { // no tag support, show the texture tree only
2541                 vbox.pack_start( textureBrowser.m_scr_win_tree, TRUE, TRUE, 0 );
2542         }
2543
2544         // TODO do we need this?
2545         //gtk_container_set_focus_chain(GTK_CONTAINER(hbox_table), NULL);
2546
2547         isWindowConstructed = true;
2548
2549         return table;
2550 }
2551
2552 void TextureBrowser_destroyGLWidget(){
2553         TextureBrowser &textureBrowser = GlobalTextureBrowser();
2554         if ( isGLWidgetConstructed )
2555         {
2556                 g_signal_handler_disconnect( G_OBJECT( textureBrowser.m_gl_widget ), textureBrowser.m_sizeHandler );
2557                 g_signal_handler_disconnect( G_OBJECT( textureBrowser.m_gl_widget ), textureBrowser.m_exposeHandler );
2558
2559 #ifdef WORKAROUND_MACOS_GTK2_GLWIDGET
2560                 textureBrowser.m_hframe.remove( textureBrowser.m_gl_widget );
2561 #else // !WORKAROUND_MACOS_GTK2_GLWIDGET
2562                 textureBrowser.m_frame.remove( textureBrowser.m_gl_widget );
2563 #endif // !WORKAROUND_MACOS_GTK2_GLWIDGET
2564
2565                 textureBrowser.m_gl_widget.unref();
2566
2567                 isGLWidgetConstructed = false;
2568         }
2569 }
2570
2571 void TextureBrowser_destroyWindow(){
2572         GlobalShaderSystem().setActiveShadersChangedNotify( Callback<void()>() );
2573
2574         TextureBrowser_destroyGLWidget();
2575 }
2576
2577 #ifdef WORKAROUND_MACOS_GTK2_GLWIDGET
2578 /* workaround for gtkglext on gtk 2 issue: OpenGL texture viewport being drawn over the other pages */
2579 /* this is very ugly: force the resizing of the viewport to a single bottom line by forcing the
2580  * resizing of the gl widget by expanding some empty boxes, so the widget area size is reduced
2581  * while covered by another page, so the texture viewport is still rendered over the other page
2582  * but does not annoy the user that much because it's just a line on the bottom that may even
2583  * be printed over existing bottom frame or very close to it. */
2584 void TextureBrowser_showGLWidget(){
2585         TextureBrowser &textureBrowser = GlobalTextureBrowser();
2586         if ( isWindowConstructed && isGLWidgetConstructed )
2587         {
2588                 textureBrowser.m_vframe.set_child_packing( textureBrowser.m_vfiller, FALSE, FALSE, 0, ui::Packing::START );
2589                 textureBrowser.m_vframe.set_child_packing( textureBrowser.m_hframe, TRUE, TRUE, 0, ui::Packing::START );
2590                 textureBrowser.m_vframe.set_child_packing( textureBrowser.m_hfiller, FALSE, FALSE, 0, ui::Packing::START );
2591                 textureBrowser.m_vframe.set_child_packing( textureBrowser.m_gl_widget, TRUE, TRUE, 0, ui::Packing::START );
2592
2593                 textureBrowser.m_gl_widget.show();
2594 }
2595 }
2596
2597 void TextureBrowser_hideGLWidget(){
2598         TextureBrowser &textureBrowser = GlobalTextureBrowser();
2599         if ( isWindowConstructed && isGLWidgetConstructed )
2600         {
2601                 textureBrowser.m_vframe.set_child_packing( textureBrowser.m_vfiller, TRUE, TRUE, 0, ui::Packing::START);
2602                 textureBrowser.m_vframe.set_child_packing( textureBrowser.m_hframe, FALSE, FALSE, 0, ui::Packing::END );
2603                 textureBrowser.m_vframe.set_child_packing( textureBrowser.m_hfiller, TRUE, TRUE, 0, ui::Packing::START);
2604                 textureBrowser.m_vframe.set_child_packing( textureBrowser.m_gl_widget, FALSE, FALSE, 0, ui::Packing::END );
2605
2606                 // The hack needs the GL widget to not be hidden to work,
2607                 // so resizing it triggers the redraw of it with the new size.
2608                 // GlobalTextureBrowser().m_gl_widget.hide();
2609
2610                 // Trigger the redraw.
2611                 TextureBrowser_redraw( &GlobalTextureBrowser() );
2612                 ui::process();
2613         }
2614 }
2615 #endif // WORKAROUND_MACOS_GTK2_GLWIDGET
2616
2617 const Vector3& TextureBrowser_getBackgroundColour( TextureBrowser& textureBrowser ){
2618         return textureBrowser.color_textureback;
2619 }
2620
2621 void TextureBrowser_setBackgroundColour( TextureBrowser& textureBrowser, const Vector3& colour ){
2622         textureBrowser.color_textureback = colour;
2623         TextureBrowser_queueDraw( textureBrowser );
2624 }
2625
2626 void TextureBrowser_selectionHelper( ui::TreeModel model, ui::TreePath path, GtkTreeIter* iter, GSList** selected ){
2627         g_assert( selected != NULL );
2628
2629         gchar* name;
2630         gtk_tree_model_get( model, iter, TAG_COLUMN, &name, -1 );
2631         *selected = g_slist_append( *selected, name );
2632 }
2633
2634 void TextureBrowser_shaderInfo(){
2635         const char* name = TextureBrowser_GetSelectedShader( GlobalTextureBrowser() );
2636         IShader* shader = QERApp_Shader_ForName( name );
2637
2638         DoShaderInfoDlg( name, shader->getShaderFileName(), "Shader Info" );
2639
2640         shader->DecRef();
2641 }
2642
2643 void TextureBrowser_addTag(){
2644         CopiedString tag;
2645         TextureBrowser &textureBrowser = GlobalTextureBrowser();
2646
2647         EMessageBoxReturn result = DoShaderTagDlg( &tag, "Add shader tag" );
2648
2649         if ( result == eIDOK && !tag.empty() ) {
2650                 GtkTreeIter iter;
2651                 textureBrowser.m_all_tags.insert( tag.c_str() );
2652                 gtk_list_store_append( textureBrowser.m_available_store, &iter );
2653                 gtk_list_store_set( textureBrowser.m_available_store, &iter, TAG_COLUMN, tag.c_str(), -1 );
2654
2655                 // Select the currently added tag in the available list
2656         auto selection = gtk_tree_view_get_selection(textureBrowser.m_available_tree );
2657                 gtk_tree_selection_select_iter( selection, &iter );
2658
2659                 textureBrowser.m_all_tags_list.append(TAG_COLUMN, tag.c_str());
2660         }
2661 }
2662
2663 void TextureBrowser_renameTag(){
2664         /* WORKAROUND: The tag treeview is set to GTK_SELECTION_MULTIPLE. Because
2665            gtk_tree_selection_get_selected() doesn't work with GTK_SELECTION_MULTIPLE,
2666            we need to count the number of selected rows first and use
2667            gtk_tree_selection_selected_foreach() then to go through the list of selected
2668            rows (which always containins a single row).
2669          */
2670
2671         GSList* selected = NULL;
2672         TextureBrowser &textureBrowser = GlobalTextureBrowser();
2673
2674         auto selection = gtk_tree_view_get_selection(textureBrowser.m_treeViewTags );
2675         gtk_tree_selection_selected_foreach( selection, GtkTreeSelectionForeachFunc( TextureBrowser_selectionHelper ), &selected );
2676
2677         if ( g_slist_length( selected ) == 1 ) { // we only rename a single tag
2678                 CopiedString newTag;
2679                 EMessageBoxReturn result = DoShaderTagDlg( &newTag, "Rename shader tag" );
2680
2681                 if ( result == eIDOK && !newTag.empty() ) {
2682                         GtkTreeIter iterList;
2683                         gchar* rowTag;
2684                         gchar* oldTag = (char*)selected->data;
2685
2686                         bool row = gtk_tree_model_get_iter_first(textureBrowser.m_all_tags_list, &iterList ) != 0;
2687
2688                         while ( row )
2689                         {
2690                                 gtk_tree_model_get(textureBrowser.m_all_tags_list, &iterList, TAG_COLUMN, &rowTag, -1 );
2691
2692                                 if ( strcmp( rowTag, oldTag ) == 0 ) {
2693                                         gtk_list_store_set( textureBrowser.m_all_tags_list, &iterList, TAG_COLUMN, newTag.c_str(), -1 );
2694                                 }
2695                                 row = gtk_tree_model_iter_next(textureBrowser.m_all_tags_list, &iterList ) != 0;
2696                         }
2697
2698                         TagBuilder.RenameShaderTag( oldTag, newTag.c_str() );
2699
2700                         textureBrowser.m_all_tags.erase( (CopiedString)oldTag );
2701                         textureBrowser.m_all_tags.insert( newTag );
2702
2703                         BuildStoreAssignedTags( textureBrowser.m_assigned_store, textureBrowser.shader.c_str(), &textureBrowser );
2704                         BuildStoreAvailableTags( textureBrowser.m_available_store, textureBrowser.m_assigned_store, textureBrowser.m_all_tags, &textureBrowser );
2705                 }
2706         }
2707         else
2708         {
2709                 ui::alert( textureBrowser.m_parent, "Select a single tag for renaming." );
2710         }
2711 }
2712
2713 void TextureBrowser_deleteTag(){
2714         GSList* selected = NULL;
2715         TextureBrowser &textureBrowser = GlobalTextureBrowser();
2716
2717         auto selection = gtk_tree_view_get_selection(textureBrowser.m_treeViewTags );
2718         gtk_tree_selection_selected_foreach( selection, GtkTreeSelectionForeachFunc( TextureBrowser_selectionHelper ), &selected );
2719
2720         if ( g_slist_length( selected ) == 1 ) { // we only delete a single tag
2721                 auto result = ui::alert( textureBrowser.m_parent, "Are you sure you want to delete the selected tag?", "Delete Tag", ui::alert_type::YESNO, ui::alert_icon::Question );
2722
2723                 if ( result == ui::alert_response::YES ) {
2724                         GtkTreeIter iterSelected;
2725                         gchar *rowTag;
2726
2727                         gchar* tagSelected = (char*)selected->data;
2728
2729                         bool row = gtk_tree_model_get_iter_first(textureBrowser.m_all_tags_list, &iterSelected ) != 0;
2730
2731                         while ( row )
2732                         {
2733                                 gtk_tree_model_get(textureBrowser.m_all_tags_list, &iterSelected, TAG_COLUMN, &rowTag, -1 );
2734
2735                                 if ( strcmp( rowTag, tagSelected ) == 0 ) {
2736                                         gtk_list_store_remove( textureBrowser.m_all_tags_list, &iterSelected );
2737                                         break;
2738                                 }
2739                                 row = gtk_tree_model_iter_next(textureBrowser.m_all_tags_list, &iterSelected ) != 0;
2740                         }
2741
2742                         TagBuilder.DeleteTag( tagSelected );
2743                         textureBrowser.m_all_tags.erase( (CopiedString)tagSelected );
2744
2745                         BuildStoreAssignedTags( textureBrowser.m_assigned_store, textureBrowser.shader.c_str(), &textureBrowser );
2746                         BuildStoreAvailableTags( textureBrowser.m_available_store, textureBrowser.m_assigned_store, textureBrowser.m_all_tags, &textureBrowser );
2747                 }
2748         }
2749         else {
2750                 ui::alert( textureBrowser.m_parent, "Select a single tag for deletion." );
2751         }
2752 }
2753
2754 void TextureBrowser_copyTag(){
2755         TextureBrowser &textureBrowser = GlobalTextureBrowser();
2756         textureBrowser.m_copied_tags.clear();
2757         TagBuilder.GetShaderTags( textureBrowser.shader.c_str(), textureBrowser.m_copied_tags );
2758 }
2759
2760 void TextureBrowser_pasteTag(){
2761         TextureBrowser &textureBrowser = GlobalTextureBrowser();
2762         IShader* ishader = QERApp_Shader_ForName( textureBrowser.shader.c_str() );
2763         CopiedString shader = textureBrowser.shader.c_str();
2764
2765         if ( !TagBuilder.CheckShaderTag( shader.c_str() ) ) {
2766                 CopiedString shaderFile = ishader->getShaderFileName();
2767                 if ( shaderFile.empty() ) {
2768                         // it's a texture
2769                         TagBuilder.AddShaderNode( shader.c_str(), CUSTOM, TEXTURE );
2770                 }
2771                 else
2772                 {
2773                         // it's a shader
2774                         TagBuilder.AddShaderNode( shader.c_str(), CUSTOM, SHADER );
2775                 }
2776
2777                 for ( size_t i = 0; i < textureBrowser.m_copied_tags.size(); ++i )
2778                 {
2779                         TagBuilder.AddShaderTag( shader.c_str(), textureBrowser.m_copied_tags[i].c_str(), TAG );
2780                 }
2781         }
2782         else
2783         {
2784                 for ( size_t i = 0; i < textureBrowser.m_copied_tags.size(); ++i )
2785                 {
2786                         if ( !TagBuilder.CheckShaderTag( shader.c_str(), textureBrowser.m_copied_tags[i].c_str() ) ) {
2787                                 // the tag doesn't exist - let's add it
2788                                 TagBuilder.AddShaderTag( shader.c_str(), textureBrowser.m_copied_tags[i].c_str(), TAG );
2789                         }
2790                 }
2791         }
2792
2793         ishader->DecRef();
2794
2795         TagBuilder.SaveXmlDoc();
2796         BuildStoreAssignedTags( textureBrowser.m_assigned_store, shader.c_str(), &textureBrowser );
2797         BuildStoreAvailableTags( textureBrowser.m_available_store, textureBrowser.m_assigned_store, textureBrowser.m_all_tags, &textureBrowser );
2798 }
2799
2800 void TextureBrowser_RefreshShaders(){
2801         TextureBrowser &textureBrowser = GlobalTextureBrowser();
2802
2803         /* When shaders are refreshed, forces reloading the textures as well.
2804         Previously it would at best only display shaders, at worst mess up some textured objects. */
2805
2806     auto selection = gtk_tree_view_get_selection(GlobalTextureBrowser().m_treeViewTree);
2807         GtkTreeModel* model = NULL;
2808         GtkTreeIter iter;
2809         if ( gtk_tree_selection_get_selected (selection, &model, &iter) )
2810         {
2811                 gchar dirName[1024];
2812
2813                 gchar* buffer;
2814                 gtk_tree_model_get( model, &iter, 0, &buffer, -1 );
2815                 strcpy( dirName, buffer );
2816                 g_free( buffer );
2817                 if ( !TextureBrowser_showWads() ) {
2818                         strcat( dirName, "/" );
2819                 }
2820
2821                 ScopeDisableScreenUpdates disableScreenUpdates( "Processing...", "Loading Shaders" );
2822                 GlobalShaderSystem().refresh();
2823                 /* texturebrowser tree update on vfs restart */
2824                 TextureBrowser_constructTreeStore();
2825                 UpdateAllWindows();
2826
2827                 TextureBrowser_ShowDirectory( GlobalTextureBrowser(), dirName );
2828                 TextureBrowser_queueDraw( GlobalTextureBrowser() );
2829         }
2830
2831         else{
2832                 ScopeDisableScreenUpdates disableScreenUpdates( "Processing...", "Loading Shaders" );
2833                 GlobalShaderSystem().refresh();
2834                 /* texturebrowser tree update on vfs restart */
2835                 TextureBrowser_constructTreeStore();
2836                 UpdateAllWindows();
2837         }
2838 }
2839
2840 void TextureBrowser_ToggleShowShaders(){
2841         GlobalTextureBrowser().m_showShaders ^= 1;
2842         GlobalTextureBrowser().m_showshaders_item.update();
2843
2844         GlobalTextureBrowser().m_heightChanged = true;
2845         GlobalTextureBrowser().m_originInvalid = true;
2846         g_activeShadersChangedCallbacks();
2847
2848         TextureBrowser_queueDraw( GlobalTextureBrowser() );
2849 }
2850
2851 void TextureBrowser_ToggleShowTextures(){
2852         GlobalTextureBrowser().m_showTextures ^= 1;
2853         GlobalTextureBrowser().m_showtextures_item.update();
2854
2855         GlobalTextureBrowser().m_heightChanged = true;
2856         GlobalTextureBrowser().m_originInvalid = true;
2857         g_activeShadersChangedCallbacks();
2858
2859         TextureBrowser_queueDraw( GlobalTextureBrowser() );
2860 }
2861
2862 void TextureBrowser_ToggleShowShaderListOnly(){
2863         g_TextureBrowser_shaderlistOnly ^= 1;
2864         GlobalTextureBrowser().m_showshaderlistonly_item.update();
2865
2866         TextureBrowser_constructTreeStore();
2867 }
2868
2869 void TextureBrowser_showAll(){
2870         g_TextureBrowser_currentDirectory = "";
2871         GlobalTextureBrowser().m_searchedTags = false;
2872 //      TextureBrowser_SetHideUnused( GlobalTextureBrowser(), false );
2873         TextureBrowser_ToggleHideUnused();
2874         //TextureBrowser_heightChanged( GlobalTextureBrowser() );
2875         TextureBrowser_updateTitle();
2876 }
2877
2878 void TextureBrowser_showUntagged(){
2879         TextureBrowser &textureBrowser = GlobalTextureBrowser();
2880         auto result = ui::alert( textureBrowser.m_parent, "WARNING! This function might need a lot of memory and time. Are you sure you want to use it?", "Show Untagged", ui::alert_type::YESNO, ui::alert_icon::Warning );
2881
2882         if ( result == ui::alert_response::YES ) {
2883                 textureBrowser.m_found_shaders.clear();
2884                 TagBuilder.GetUntagged( textureBrowser.m_found_shaders );
2885                 std::set<CopiedString>::iterator iter;
2886
2887                 ScopeDisableScreenUpdates disableScreenUpdates( "Searching untagged textures...", "Loading Textures" );
2888
2889                 for ( iter = textureBrowser.m_found_shaders.begin(); iter != textureBrowser.m_found_shaders.end(); iter++ )
2890                 {
2891                         std::string path = ( *iter ).c_str();
2892                         size_t pos = path.find_last_of( "/", path.size() );
2893                         std::string name = path.substr( pos + 1, path.size() );
2894                         path = path.substr( 0, pos + 1 );
2895                         TextureDirectory_loadTexture( path.c_str(), name.c_str() );
2896                         globalErrorStream() << path.c_str() << name.c_str() << "\n";
2897                 }
2898
2899                 g_TextureBrowser_currentDirectory = "Untagged";
2900                 TextureBrowser_queueDraw( GlobalTextureBrowser() );
2901                 TextureBrowser_heightChanged( textureBrowser );
2902                 TextureBrowser_updateTitle();
2903         }
2904 }
2905
2906 void TextureBrowser_FixedSize(){
2907         g_TextureBrowser_fixedSize ^= 1;
2908         GlobalTextureBrowser().m_fixedsize_item.update();
2909         TextureBrowser_activeShadersChanged( GlobalTextureBrowser() );
2910 }
2911
2912 void TextureBrowser_FilterMissing(){
2913         g_TextureBrowser_filterMissing ^= 1;
2914         GlobalTextureBrowser().m_filternotex_item.update();
2915         TextureBrowser_activeShadersChanged( GlobalTextureBrowser() );
2916         TextureBrowser_RefreshShaders();
2917 }
2918
2919 void TextureBrowser_FilterFallback(){
2920         g_TextureBrowser_filterFallback ^= 1;
2921         GlobalTextureBrowser().m_hidenotex_item.update();
2922         TextureBrowser_activeShadersChanged( GlobalTextureBrowser() );
2923         TextureBrowser_RefreshShaders();
2924 }
2925
2926 void TextureBrowser_EnableAlpha(){
2927         g_TextureBrowser_enableAlpha ^= 1;
2928         GlobalTextureBrowser().m_enablealpha_item.update();
2929         TextureBrowser_activeShadersChanged( GlobalTextureBrowser() );
2930 }
2931
2932 void TextureBrowser_exportTitle( const Callback<void(const char *)> & importer ){
2933         StringOutputStream buffer( 64 );
2934         buffer << "Textures: ";
2935         if ( !string_empty( g_TextureBrowser_currentDirectory.c_str() ) ) {
2936                 buffer << g_TextureBrowser_currentDirectory.c_str();
2937         }
2938         else
2939         {
2940                 buffer << "all";
2941         }
2942         importer( buffer.c_str() );
2943 }
2944
2945 struct TextureScale {
2946         static void Export(const TextureBrowser &self, const Callback<void(int)> &returnz) {
2947                 switch (self.m_textureScale) {
2948                         case 10:
2949                                 returnz(0);
2950                                 break;
2951                         case 25:
2952                                 returnz(1);
2953                                 break;
2954                         case 50:
2955                                 returnz(2);
2956                                 break;
2957                         case 100:
2958                                 returnz(3);
2959                                 break;
2960                         case 200:
2961                                 returnz(4);
2962                                 break;
2963                 }
2964         }
2965
2966         static void Import(TextureBrowser &self, int value) {
2967                 switch (value) {
2968                         case 0:
2969                                 TextureBrowser_setScale(self, 10);
2970                                 break;
2971                         case 1:
2972                                 TextureBrowser_setScale(self, 25);
2973                                 break;
2974                         case 2:
2975                                 TextureBrowser_setScale(self, 50);
2976                                 break;
2977                         case 3:
2978                                 TextureBrowser_setScale(self, 100);
2979                                 break;
2980                         case 4:
2981                                 TextureBrowser_setScale(self, 200);
2982                                 break;
2983                 }
2984         }
2985 };
2986
2987 struct UniformTextureSize {
2988         static void Export(const TextureBrowser &self, const Callback<void(int)> &returnz) {
2989                 returnz(GlobalTextureBrowser().m_uniformTextureSize);
2990         }
2991
2992         static void Import(TextureBrowser &self, int value) {
2993                 if (value > 16)
2994                         TextureBrowser_setUniformSize(self, value);
2995         }
2996 };
2997
2998 struct UniformTextureMinSize {
2999         static void Export(const TextureBrowser &self, const Callback<void(int)> &returnz) {
3000                 returnz(GlobalTextureBrowser().m_uniformTextureMinSize);
3001         }
3002
3003         static void Import(TextureBrowser &self, int value) {
3004                 if (value > 16)
3005                         TextureBrowser_setUniformSize(self, value);
3006         }
3007 };
3008
3009 void TextureBrowser_constructPreferences( PreferencesPage& page ){
3010         page.appendCheckBox(
3011                 "", "Texture scrollbar",
3012                 make_property<TextureBrowser_ShowScrollbar>(GlobalTextureBrowser())
3013                 );
3014         {
3015                 const char* texture_scale[] = { "10%", "25%", "50%", "100%", "200%" };
3016                 page.appendCombo(
3017                         "Texture Thumbnail Scale",
3018                         STRING_ARRAY_RANGE( texture_scale ),
3019                         make_property<TextureScale>(GlobalTextureBrowser())
3020                         );
3021         }
3022         page.appendSpinner( "Thumbnails Max Size", GlobalTextureBrowser().m_uniformTextureSize, GlobalTextureBrowser().m_uniformTextureSize, 16, 8192 );
3023         page.appendSpinner( "Thumbnails Min Size", GlobalTextureBrowser().m_uniformTextureMinSize, GlobalTextureBrowser().m_uniformTextureMinSize, 16, 8192 );
3024         page.appendEntry( "Mousewheel Increment", GlobalTextureBrowser().m_mouseWheelScrollIncrement );
3025         {
3026                 const char* startup_shaders[] = { "None", TextureBrowser_getCommonShadersName() };
3027                 page.appendCombo( "Load Shaders at Startup", reinterpret_cast<int&>( GlobalTextureBrowser().m_startupShaders ), STRING_ARRAY_RANGE( startup_shaders ) );
3028         }
3029 }
3030
3031 void TextureBrowser_constructPage( PreferenceGroup& group ){
3032         PreferencesPage page( group.createPage( "Texture Browser", "Texture Browser Preferences" ) );
3033         TextureBrowser_constructPreferences( page );
3034 }
3035
3036 void TextureBrowser_registerPreferencesPage(){
3037         PreferencesDialog_addSettingsPage( makeCallbackF(TextureBrowser_constructPage) );
3038 }
3039
3040
3041 #include "preferencesystem.h"
3042 #include "stringio.h"
3043
3044
3045 void TextureClipboard_textureSelected( const char* shader );
3046
3047 void TextureBrowser_Construct(){
3048         TextureBrowser &textureBrowser = GlobalTextureBrowser();
3049
3050         GlobalCommands_insert( "ShaderInfo", makeCallbackF(TextureBrowser_shaderInfo) );
3051         GlobalCommands_insert( "ShowUntagged", makeCallbackF(TextureBrowser_showUntagged) );
3052         GlobalCommands_insert( "AddTag", makeCallbackF(TextureBrowser_addTag) );
3053         GlobalCommands_insert( "RenameTag", makeCallbackF(TextureBrowser_renameTag) );
3054         GlobalCommands_insert( "DeleteTag", makeCallbackF(TextureBrowser_deleteTag) );
3055         GlobalCommands_insert( "CopyTag", makeCallbackF(TextureBrowser_copyTag) );
3056         GlobalCommands_insert( "PasteTag", makeCallbackF(TextureBrowser_pasteTag) );
3057         GlobalCommands_insert( "RefreshShaders", makeCallbackF(VFS_Refresh) );
3058         GlobalToggles_insert( "ShowInUse", makeCallbackF(TextureBrowser_ToggleHideUnused), ToggleItem::AddCallbackCaller( textureBrowser.m_hideunused_item ), Accelerator( 'U' ) );
3059         GlobalCommands_insert( "ShowAllTextures", makeCallbackF(TextureBrowser_showAll), Accelerator( 'A', (GdkModifierType)GDK_CONTROL_MASK ) );
3060         GlobalCommands_insert( "ToggleTextures", makeCallbackF(TextureBrowser_toggleShow), Accelerator( 'T' ) );
3061         GlobalToggles_insert( "ToggleShowShaders", makeCallbackF(TextureBrowser_ToggleShowShaders), ToggleItem::AddCallbackCaller( GlobalTextureBrowser().m_showshaders_item ) );
3062         GlobalToggles_insert( "ToggleShowTextures", makeCallbackF(TextureBrowser_ToggleShowTextures), ToggleItem::AddCallbackCaller( GlobalTextureBrowser().m_showtextures_item ) );
3063         GlobalToggles_insert( "ToggleShowShaderlistOnly", makeCallbackF(TextureBrowser_ToggleShowShaderListOnly),
3064  ToggleItem::AddCallbackCaller( GlobalTextureBrowser().m_showshaderlistonly_item ) );
3065         GlobalToggles_insert( "FixedSize", makeCallbackF(TextureBrowser_FixedSize), ToggleItem::AddCallbackCaller( GlobalTextureBrowser().m_fixedsize_item ) );
3066         GlobalToggles_insert( "FilterMissing", makeCallbackF(TextureBrowser_FilterMissing), ToggleItem::AddCallbackCaller( GlobalTextureBrowser().m_filternotex_item ) );
3067         GlobalToggles_insert( "FilterFallback", makeCallbackF(TextureBrowser_FilterFallback), ToggleItem::AddCallbackCaller( GlobalTextureBrowser().m_hidenotex_item ) );
3068         GlobalToggles_insert( "EnableAlpha", makeCallbackF(TextureBrowser_EnableAlpha), ToggleItem::AddCallbackCaller( GlobalTextureBrowser().m_enablealpha_item ) );
3069
3070         GlobalPreferenceSystem().registerPreference( "TextureScale", make_property_string<TextureScale>(textureBrowser) );
3071         GlobalPreferenceSystem().registerPreference( "UniformTextureSize", make_property_string<UniformTextureSize>(textureBrowser) );
3072         GlobalPreferenceSystem().registerPreference( "UniformTextureMinSize", make_property_string<UniformTextureMinSize>(textureBrowser) );
3073         GlobalPreferenceSystem().registerPreference( "TextureScrollbar", make_property_string<TextureBrowser_ShowScrollbar>(textureBrowser));
3074         GlobalPreferenceSystem().registerPreference( "ShowShaders", make_property_string( textureBrowser.m_showShaders ) );
3075         GlobalPreferenceSystem().registerPreference( "ShowTextures", make_property_string( GlobalTextureBrowser().m_showTextures ) );
3076         GlobalPreferenceSystem().registerPreference( "ShowShaderlistOnly", make_property_string( g_TextureBrowser_shaderlistOnly ) );
3077         GlobalPreferenceSystem().registerPreference( "FixedSize", make_property_string( g_TextureBrowser_fixedSize ) );
3078         GlobalPreferenceSystem().registerPreference( "FilterMissing", make_property_string( g_TextureBrowser_filterMissing ) );
3079         GlobalPreferenceSystem().registerPreference( "EnableAlpha", make_property_string( g_TextureBrowser_enableAlpha ) );
3080         GlobalPreferenceSystem().registerPreference( "LoadShaders", make_property_string( reinterpret_cast<int&>( textureBrowser.m_startupShaders ) ) );
3081         GlobalPreferenceSystem().registerPreference( "WheelMouseInc", make_property_string( textureBrowser.m_mouseWheelScrollIncrement ) );
3082         GlobalPreferenceSystem().registerPreference( "SI_Colors0", make_property_string( textureBrowser.color_textureback ) );
3083
3084         textureBrowser.shader = texdef_name_default();
3085
3086         Textures_setModeChangedNotify( ReferenceCaller<TextureBrowser, void(), TextureBrowser_queueDraw>( textureBrowser ) );
3087
3088         TextureBrowser_registerPreferencesPage();
3089
3090         GlobalShaderSystem().attach( g_ShadersObserver );
3091
3092         TextureBrowser_textureSelected = TextureClipboard_textureSelected;
3093 }
3094
3095 void TextureBrowser_Destroy(){
3096         GlobalShaderSystem().detach( g_ShadersObserver );
3097
3098         Textures_setModeChangedNotify( Callback<void()>() );
3099 }
3100
3101 ui::Widget TextureBrowser_getGLWidget(){
3102         return GlobalTextureBrowser().m_gl_widget;
3103 }
3104
3105 #if WORKAROUND_WINDOWS_GTK2_GLWIDGET
3106 ui::GLArea TextureBrowser_getGLWidget(){
3107         return GlobalTextureBrowser().m_gl_widget;
3108 }
3109 #endif // WORKAROUND_WINDOWS_GTK2_GLWIDGET