]> de.git.xonotic.org Git - xonotic/netradiant.git/blob - radiant/texwindow.cpp
Merge commit 'c5065eecd29651649c2f3d04be8af9a19d189733' 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 && event->button == 1 ) {
1583                 #define GARUX_DISABLE_2BUTTON
1584                 #ifndef GARUX_DISABLE_2BUTTON
1585                 CopiedString texName = textureBrowser->shader;
1586                 const char* sh = textureBrowser->shader.c_str();
1587                 char* dir = strrchr( sh, '/' );
1588                 if( dir != NULL ){
1589                         *(dir + 1) = '\0';
1590                         dir = strchr( sh, '/' );
1591                         if( dir != NULL ){
1592                                 dir++;
1593                                 if( *dir != '\0'){
1594                                         ScopeDisableScreenUpdates disableScreenUpdates( dir, "Loading Textures" );
1595                                         TextureBrowser_ShowDirectory( *textureBrowser, dir );
1596                                         TextureBrowser_Focus( *textureBrowser, textureBrowser->shader.c_str() );
1597                                         TextureBrowser_queueDraw( *textureBrowser );
1598                                 }
1599                         }
1600                 }
1601                 #endif
1602         }
1603         else if ( event->type == GDK_2BUTTON_PRESS && event->button == 3 ) {
1604                 ScopeDisableScreenUpdates disableScreenUpdates( TextureBrowser_getCommonShadersDir(), "Loading Textures" );
1605                 TextureBrowser_ShowDirectory( *textureBrowser, TextureBrowser_getCommonShadersDir() );
1606                 TextureBrowser_queueDraw( *textureBrowser );
1607         }
1608         return FALSE;
1609 }
1610
1611 gboolean TextureBrowser_button_release( ui::Widget widget, GdkEventButton* event, TextureBrowser* textureBrowser ){
1612         if ( event->type == GDK_BUTTON_RELEASE ) {
1613                 if ( event->button == 3 ) {
1614                         if ( !textureBrowser->m_tags ) {
1615                                 TextureBrowser_Tracking_MouseUp( *textureBrowser );
1616                         }
1617                 }
1618         }
1619         return FALSE;
1620 }
1621
1622 gboolean TextureBrowser_motion( ui::Widget widget, GdkEventMotion *event, TextureBrowser* textureBrowser ){
1623         return FALSE;
1624 }
1625
1626 gboolean TextureBrowser_scroll( ui::Widget widget, GdkEventScroll* event, TextureBrowser* textureBrowser ){
1627         if ( event->direction == GDK_SCROLL_UP ) {
1628                 TextureBrowser_MouseWheel( *textureBrowser, true );
1629         }
1630         else if ( event->direction == GDK_SCROLL_DOWN ) {
1631                 TextureBrowser_MouseWheel( *textureBrowser, false );
1632         }
1633         return FALSE;
1634 }
1635
1636 void TextureBrowser_scrollChanged( void* data, gdouble value ){
1637         //globalOutputStream() << "vertical scroll\n";
1638         TextureBrowser_setOriginY( *reinterpret_cast<TextureBrowser*>( data ), -(int)value );
1639 }
1640
1641 static void TextureBrowser_verticalScroll(ui::Adjustment adjustment, TextureBrowser* textureBrowser ){
1642         textureBrowser->m_scrollAdjustment.value_changed( gtk_adjustment_get_value(adjustment) );
1643 }
1644
1645 void TextureBrowser_updateScroll( TextureBrowser& textureBrowser ){
1646         if ( textureBrowser.m_showTextureScrollbar ) {
1647                 int totalHeight = TextureBrowser_TotalHeight( textureBrowser );
1648
1649                 totalHeight = std::max( totalHeight, textureBrowser.height );
1650
1651         auto vadjustment = gtk_range_get_adjustment( GTK_RANGE( textureBrowser.m_texture_scroll ) );
1652
1653                 gtk_adjustment_set_value(vadjustment, -TextureBrowser_getOriginY( textureBrowser ));
1654                 gtk_adjustment_set_page_size(vadjustment, textureBrowser.height);
1655                 gtk_adjustment_set_page_increment(vadjustment, textureBrowser.height / 2);
1656                 gtk_adjustment_set_step_increment(vadjustment, 20);
1657                 gtk_adjustment_set_lower(vadjustment, 0);
1658                 gtk_adjustment_set_upper(vadjustment, totalHeight);
1659
1660                 g_signal_emit_by_name( G_OBJECT( vadjustment ), "changed" );
1661         }
1662 }
1663
1664 gboolean TextureBrowser_size_allocate( ui::Widget widget, GtkAllocation* allocation, TextureBrowser* textureBrowser ){
1665         textureBrowser->width = allocation->width;
1666         textureBrowser->height = allocation->height;
1667         TextureBrowser_heightChanged( *textureBrowser );
1668         textureBrowser->m_originInvalid = true;
1669         TextureBrowser_queueDraw( *textureBrowser );
1670         return FALSE;
1671 }
1672
1673 void TextureBrowser_redraw( TextureBrowser* textureBrowser ){
1674         if ( glwidget_make_current( textureBrowser->m_gl_widget ) != FALSE ) {
1675                 GlobalOpenGL_debugAssertNoErrors();
1676                 TextureBrowser_evaluateHeight( *textureBrowser );
1677                 Texture_Draw( *textureBrowser );
1678                 GlobalOpenGL_debugAssertNoErrors();
1679                 glwidget_swap_buffers( textureBrowser->m_gl_widget );
1680         }
1681 }
1682
1683 gboolean TextureBrowser_expose( ui::Widget widget, GdkEventExpose* event, TextureBrowser* textureBrowser ){
1684         TextureBrowser_redraw( textureBrowser );
1685         return FALSE;
1686 }
1687
1688 TextureBrowser& GlobalTextureBrowser(){
1689         static TextureBrowser textureBrowser;
1690         return textureBrowser;
1691 }
1692
1693 bool TextureBrowser_hideUnused(){
1694         return GlobalTextureBrowser().m_hideUnused;
1695 }
1696
1697 void TextureBrowser_ToggleHideUnused(){
1698         TextureBrowser &textureBrowser = GlobalTextureBrowser();
1699         if ( textureBrowser.m_hideUnused ) {
1700                 TextureBrowser_SetHideUnused( textureBrowser, false );
1701         }
1702         else
1703         {
1704                 TextureBrowser_SetHideUnused( textureBrowser, true );
1705         }
1706 }
1707
1708 const char* TextureGroups_transformDirName( const char* dirName, StringOutputStream *archiveName )
1709 {
1710         if ( TextureBrowser_showWads() ) {
1711                 archiveName->clear();
1712                 *archiveName << StringRange( path_get_filename_start( dirName ), path_get_filename_base_end( dirName ) ) \
1713                         << "." << path_get_extension( dirName );
1714                 return archiveName->c_str();
1715         }
1716         return dirName;
1717 }
1718
1719 void TextureGroups_constructTreeModel( TextureGroups groups, ui::TreeStore store ){
1720         // put the information from the old textures menu into a treeview
1721         GtkTreeIter iter, child;
1722
1723         TextureGroups::const_iterator i = groups.begin();
1724         while ( i != groups.end() )
1725         {
1726                 StringOutputStream archiveName;
1727                 StringOutputStream nextArchiveName;
1728                 const char* dirName = TextureGroups_transformDirName( ( *i ).c_str(), &archiveName );
1729
1730                 const char* firstUnderscore = strchr( dirName, '_' );
1731                 StringRange dirRoot( dirName, ( firstUnderscore == 0 ) ? dirName : firstUnderscore + 1 );
1732
1733                 TextureGroups::const_iterator next = i;
1734                 ++next;
1735
1736                 if ( firstUnderscore != 0
1737                          && next != groups.end()
1738                          && string_equal_start( TextureGroups_transformDirName( ( *next ).c_str(), &nextArchiveName ), dirRoot ) ) {
1739                         gtk_tree_store_append( store, &iter, NULL );
1740                         gtk_tree_store_set( store, &iter, 0, CopiedString( StringRange( dirName, firstUnderscore ) ).c_str(), -1 );
1741
1742                         // keep going...
1743                         while ( i != groups.end() && string_equal_start( TextureGroups_transformDirName( ( *i ).c_str(), &nextArchiveName ), dirRoot ) )
1744                         {
1745                                 gtk_tree_store_append( store, &child, &iter );
1746                                 gtk_tree_store_set( store, &child, 0, TextureGroups_transformDirName( ( *i ).c_str(), &nextArchiveName ), -1 );
1747                                 ++i;
1748                         }
1749                 }
1750                 else
1751                 {
1752                         gtk_tree_store_append( store, &iter, NULL );
1753                         gtk_tree_store_set( store, &iter, 0, dirName, -1 );
1754                         ++i;
1755                 }
1756         }
1757 }
1758
1759 TextureGroups TextureGroups_constructTreeView(){
1760         TextureGroups groups;
1761
1762         if ( TextureBrowser_showWads() ) {
1763                 GlobalFileSystem().forEachArchive( TextureGroupsAddWadCaller( groups ) );
1764         }
1765         else
1766         {
1767                 // scan texture dirs and pak files only if not restricting to shaderlist
1768                 if ( g_pGameDescription->mGameType != "doom3" && !g_TextureBrowser_shaderlistOnly ) {
1769                         GlobalFileSystem().forEachDirectory( "textures/", TextureGroupsAddDirectoryCaller( groups ) );
1770                 }
1771
1772                 GlobalShaderSystem().foreachShaderName( TextureGroupsAddShaderCaller( groups ) );
1773         }
1774
1775         return groups;
1776 }
1777
1778 void TextureBrowser_constructTreeStore(){
1779         TextureGroups groups = TextureGroups_constructTreeView();
1780         auto store = ui::TreeStore::from(gtk_tree_store_new( 1, G_TYPE_STRING ));
1781         TextureGroups_constructTreeModel( groups, store );
1782
1783         gtk_tree_view_set_model(GlobalTextureBrowser().m_treeViewTree, store);
1784
1785         g_object_unref( G_OBJECT( store ) );
1786 }
1787
1788 void TextureBrowser_constructTreeStoreTags(){
1789         TextureGroups groups;
1790         TextureBrowser &textureBrowser = GlobalTextureBrowser();
1791         auto store = ui::TreeStore::from(gtk_tree_store_new( 1, G_TYPE_STRING ));
1792         auto model = GlobalTextureBrowser().m_all_tags_list;
1793
1794         gtk_tree_view_set_model(GlobalTextureBrowser().m_treeViewTags, model );
1795
1796         g_object_unref( G_OBJECT( store ) );
1797 }
1798
1799 void TreeView_onRowActivated( ui::TreeView treeview, ui::TreePath path, ui::TreeViewColumn col, gpointer userdata ){
1800         GtkTreeIter iter;
1801
1802     auto model = gtk_tree_view_get_model(treeview );
1803
1804         if ( gtk_tree_model_get_iter( model, &iter, path ) ) {
1805                 gchar dirName[1024];
1806
1807                 gchar* buffer;
1808                 gtk_tree_model_get( model, &iter, 0, &buffer, -1 );
1809                 strcpy( dirName, buffer );
1810                 g_free( buffer );
1811
1812                 GlobalTextureBrowser().m_searchedTags = false;
1813
1814                 if ( !TextureBrowser_showWads() ) {
1815                         strcat( dirName, "/" );
1816                 }
1817
1818                 ScopeDisableScreenUpdates disableScreenUpdates( dirName, "Loading Textures" );
1819                 TextureBrowser_ShowDirectory( GlobalTextureBrowser(), dirName );
1820                 TextureBrowser_queueDraw( GlobalTextureBrowser() );
1821                 //deactivate, so SPACE and RETURN wont be broken for 2d
1822                 gtk_window_set_focus( GTK_WINDOW( gtk_widget_get_toplevel( GTK_WIDGET( treeview ) ) ), NULL );
1823         }
1824 }
1825
1826 void TextureBrowser_createTreeViewTree(){
1827         TextureBrowser &textureBrowser = GlobalTextureBrowser();
1828         gtk_tree_view_set_enable_search(textureBrowser.m_treeViewTree, FALSE );
1829
1830         gtk_tree_view_set_headers_visible(textureBrowser.m_treeViewTree, FALSE );
1831         textureBrowser.m_treeViewTree.connect( "row-activated", (GCallback) TreeView_onRowActivated, NULL );
1832
1833         auto renderer = ui::CellRendererText(ui::New);
1834         gtk_tree_view_insert_column_with_attributes(textureBrowser.m_treeViewTree, -1, "", renderer, "text", 0, NULL );
1835
1836         TextureBrowser_constructTreeStore();
1837 }
1838
1839 void TextureBrowser_addTag();
1840
1841 void TextureBrowser_renameTag();
1842
1843 void TextureBrowser_deleteTag();
1844
1845 void TextureBrowser_createContextMenu( ui::Widget treeview, GdkEventButton *event ){
1846         ui::Widget menu = ui::Menu(ui::New);
1847
1848         ui::Widget menuitem = ui::MenuItem( "Add tag" );
1849         menuitem.connect( "activate", (GCallback)TextureBrowser_addTag, treeview );
1850         gtk_menu_shell_append( GTK_MENU_SHELL( menu ), menuitem );
1851
1852         menuitem = ui::MenuItem( "Rename tag" );
1853         menuitem.connect( "activate", (GCallback)TextureBrowser_renameTag, treeview );
1854         gtk_menu_shell_append( GTK_MENU_SHELL( menu ), menuitem );
1855
1856         menuitem = ui::MenuItem( "Delete tag" );
1857         menuitem.connect( "activate", (GCallback)TextureBrowser_deleteTag, treeview );
1858         gtk_menu_shell_append( GTK_MENU_SHELL( menu ), menuitem );
1859
1860         gtk_widget_show_all( menu );
1861
1862         gtk_menu_popup( GTK_MENU( menu ), NULL, NULL, NULL, NULL,
1863                                         ( event != NULL ) ? event->button : 0,
1864                                         gdk_event_get_time( (GdkEvent*)event ) );
1865 }
1866
1867 gboolean TreeViewTags_onButtonPressed( ui::TreeView treeview, GdkEventButton *event ){
1868         if ( event->type == GDK_BUTTON_PRESS && event->button == 3 ) {
1869                 GtkTreePath *path;
1870         auto selection = gtk_tree_view_get_selection(treeview );
1871
1872                 if ( gtk_tree_view_get_path_at_pos(treeview, event->x, event->y, &path, NULL, NULL, NULL ) ) {
1873                         gtk_tree_selection_unselect_all( selection );
1874                         gtk_tree_selection_select_path( selection, path );
1875                         gtk_tree_path_free( path );
1876                 }
1877
1878                 TextureBrowser_createContextMenu( treeview, event );
1879                 return TRUE;
1880         }
1881         return FALSE;
1882 }
1883
1884 void TextureBrowser_createTreeViewTags(){
1885         TextureBrowser &textureBrowser = GlobalTextureBrowser();
1886         textureBrowser.m_treeViewTags = ui::TreeView(ui::New);
1887         gtk_tree_view_set_enable_search(textureBrowser.m_treeViewTags, FALSE );
1888
1889         textureBrowser.m_treeViewTags.connect( "button-press-event", (GCallback)TreeViewTags_onButtonPressed, NULL );
1890
1891         gtk_tree_view_set_headers_visible(textureBrowser.m_treeViewTags, FALSE );
1892
1893         auto renderer = ui::CellRendererText(ui::New);
1894         gtk_tree_view_insert_column_with_attributes(textureBrowser.m_treeViewTags, -1, "", renderer, "text", 0, NULL );
1895
1896         TextureBrowser_constructTreeStoreTags();
1897 }
1898
1899 ui::MenuItem TextureBrowser_constructViewMenu( ui::Menu menu ){
1900         TextureBrowser &textureBrowser = GlobalTextureBrowser();
1901         ui::MenuItem textures_menu_item = ui::MenuItem(new_sub_menu_item_with_mnemonic( "_View" ));
1902
1903         if ( g_Layout_enableDetachableMenus.m_value ) {
1904                 menu_tearoff( menu );
1905         }
1906
1907         create_check_menu_item_with_mnemonic( menu, "Hide _Unused", "ShowInUse" );
1908         if ( string_empty( g_pGameDescription->getKeyValue( "show_wads" ) ) ) {
1909                 create_check_menu_item_with_mnemonic( menu, "Hide Image Missing", "FilterMissing" );
1910         }
1911
1912         // hide notex and shadernotex on texture browser: no one wants to apply them
1913         create_check_menu_item_with_mnemonic( menu, "Hide Fallback", "FilterFallback" );
1914
1915         menu_separator( menu );
1916
1917
1918         // we always want to show shaders but don't want a "Show Shaders" menu for doom3 and .wad file games
1919         if ( g_pGameDescription->mGameType == "doom3" || TextureBrowser_showWads() ) {
1920                 textureBrowser.m_showShaders = true;
1921         }
1922         else
1923         {
1924                 create_check_menu_item_with_mnemonic( menu, "Show shaders", "ToggleShowShaders" );
1925                 create_check_menu_item_with_mnemonic( menu, "Show textures", "ToggleShowTextures" );
1926                 menu_separator( menu );
1927         }
1928
1929         if ( textureBrowser.m_tags ) {
1930                 create_menu_item_with_mnemonic( menu, "Show Untagged", "ShowUntagged" );
1931         }
1932         if ( g_pGameDescription->mGameType != "doom3" && string_empty( g_pGameDescription->getKeyValue( "show_wads" ) ) ) {
1933                 create_check_menu_item_with_mnemonic( menu, "ShaderList Only", "ToggleShowShaderlistOnly" );
1934         }
1935
1936         menu_separator( menu );
1937         create_check_menu_item_with_mnemonic( menu, "Fixed Size", "FixedSize" );
1938         create_check_menu_item_with_mnemonic( menu, "Transparency", "EnableAlpha" );
1939
1940         if ( string_empty( g_pGameDescription->getKeyValue( "show_wads" ) ) ) {
1941                 menu_separator( menu );
1942                 textureBrowser.m_shader_info_item = ui::Widget(create_menu_item_with_mnemonic( menu, "Shader Info", "ShaderInfo"  ));
1943                 gtk_widget_set_sensitive( textureBrowser.m_shader_info_item, FALSE );
1944         }
1945
1946
1947         return textures_menu_item;
1948 }
1949
1950 void Popup_View_Menu( GtkWidget *widget, GtkMenu *menu ){
1951         gtk_menu_popup( menu, NULL, NULL, NULL, NULL, 1, gtk_get_current_event_time() );
1952 }
1953
1954 ui::MenuItem TextureBrowser_constructToolsMenu( ui::Menu menu ){
1955         ui::MenuItem textures_menu_item = ui::MenuItem(new_sub_menu_item_with_mnemonic( "_Tools" ));
1956
1957         if ( g_Layout_enableDetachableMenus.m_value ) {
1958                 menu_tearoff( menu );
1959         }
1960
1961         create_menu_item_with_mnemonic( menu, "Flush & Reload Shaders", "RefreshShaders" );
1962         create_menu_item_with_mnemonic( menu, "Find / Replace...", "FindReplaceTextures" );
1963
1964         return textures_menu_item;
1965 }
1966
1967 ui::MenuItem TextureBrowser_constructTagsMenu( ui::Menu menu ){
1968         ui::MenuItem textures_menu_item = ui::MenuItem(new_sub_menu_item_with_mnemonic( "T_ags" ));
1969
1970         if ( g_Layout_enableDetachableMenus.m_value ) {
1971                 menu_tearoff( menu );
1972         }
1973
1974         create_menu_item_with_mnemonic( menu, "Add tag", "AddTag" );
1975         create_menu_item_with_mnemonic( menu, "Rename tag", "RenameTag" );
1976         create_menu_item_with_mnemonic( menu, "Delete tag", "DeleteTag" );
1977         menu_separator( menu );
1978         create_menu_item_with_mnemonic( menu, "Copy tags from selected", "CopyTag" );
1979         create_menu_item_with_mnemonic( menu, "Paste tags to selected", "PasteTag" );
1980
1981         return textures_menu_item;
1982 }
1983
1984 gboolean TextureBrowser_tagMoveHelper( ui::TreeModel model, ui::TreePath path, GtkTreeIter* iter, GSList** selected ){
1985         g_assert( selected != NULL );
1986
1987     auto rowref = gtk_tree_row_reference_new( model, path );
1988         *selected = g_slist_append( *selected, rowref );
1989
1990         return FALSE;
1991 }
1992
1993 void TextureBrowser_assignTags(){
1994         GSList* selected = NULL;
1995         GSList* node;
1996         gchar* tag_assigned;
1997         TextureBrowser &textureBrowser = GlobalTextureBrowser();
1998
1999         auto selection = gtk_tree_view_get_selection(textureBrowser.m_available_tree );
2000
2001         gtk_tree_selection_selected_foreach( selection, (GtkTreeSelectionForeachFunc)TextureBrowser_tagMoveHelper, &selected );
2002
2003         if ( selected != NULL ) {
2004                 for ( node = selected; node != NULL; node = node->next )
2005                 {
2006             auto path = gtk_tree_row_reference_get_path( (GtkTreeRowReference*)node->data );
2007
2008                         if ( path ) {
2009                                 GtkTreeIter iter;
2010
2011                                 if ( gtk_tree_model_get_iter(textureBrowser.m_available_store, &iter, path ) ) {
2012                                         gtk_tree_model_get(textureBrowser.m_available_store, &iter, TAG_COLUMN, &tag_assigned, -1 );
2013                                         if ( !TagBuilder.CheckShaderTag( textureBrowser.shader.c_str() ) ) {
2014                                                 // create a custom shader/texture entry
2015                                                 IShader* ishader = QERApp_Shader_ForName( textureBrowser.shader.c_str() );
2016                                                 CopiedString filename = ishader->getShaderFileName();
2017
2018                                                 if ( filename.empty() ) {
2019                                                         // it's a texture
2020                                                         TagBuilder.AddShaderNode( textureBrowser.shader.c_str(), CUSTOM, TEXTURE );
2021                                                 }
2022                                                 else {
2023                                                         // it's a shader
2024                                                         TagBuilder.AddShaderNode( textureBrowser.shader.c_str(), CUSTOM, SHADER );
2025                                                 }
2026                                                 ishader->DecRef();
2027                                         }
2028                                         TagBuilder.AddShaderTag( textureBrowser.shader.c_str(), (char*)tag_assigned, TAG );
2029
2030                                         gtk_list_store_remove( textureBrowser.m_available_store, &iter );
2031                                         textureBrowser.m_assigned_store.append(TAG_COLUMN, tag_assigned);
2032                                 }
2033                         }
2034                 }
2035
2036                 g_slist_foreach( selected, (GFunc)gtk_tree_row_reference_free, NULL );
2037
2038                 // Save changes
2039                 TagBuilder.SaveXmlDoc();
2040         }
2041         g_slist_free( selected );
2042 }
2043
2044 void TextureBrowser_removeTags(){
2045         GSList* selected = NULL;
2046         GSList* node;
2047         gchar* tag;
2048         TextureBrowser &textureBrowser = GlobalTextureBrowser();
2049
2050         auto selection = gtk_tree_view_get_selection(textureBrowser.m_assigned_tree );
2051
2052         gtk_tree_selection_selected_foreach( selection, (GtkTreeSelectionForeachFunc)TextureBrowser_tagMoveHelper, &selected );
2053
2054         if ( selected != NULL ) {
2055                 for ( node = selected; node != NULL; node = node->next )
2056                 {
2057             auto path = gtk_tree_row_reference_get_path( (GtkTreeRowReference*)node->data );
2058
2059                         if ( path ) {
2060                                 GtkTreeIter iter;
2061
2062                                 if ( gtk_tree_model_get_iter(textureBrowser.m_assigned_store, &iter, path ) ) {
2063                                         gtk_tree_model_get(textureBrowser.m_assigned_store, &iter, TAG_COLUMN, &tag, -1 );
2064                                         TagBuilder.DeleteShaderTag( textureBrowser.shader.c_str(), tag );
2065                                         gtk_list_store_remove( textureBrowser.m_assigned_store, &iter );
2066                                 }
2067                         }
2068                 }
2069
2070                 g_slist_foreach( selected, (GFunc)gtk_tree_row_reference_free, NULL );
2071
2072                 // Update the "available tags list"
2073                 BuildStoreAvailableTags( textureBrowser.m_available_store, textureBrowser.m_assigned_store, textureBrowser.m_all_tags, &textureBrowser );
2074
2075                 // Save changes
2076                 TagBuilder.SaveXmlDoc();
2077         }
2078         g_slist_free( selected );
2079 }
2080
2081 void TextureBrowser_buildTagList(){
2082         TextureBrowser &textureBrowser = GlobalTextureBrowser();
2083         textureBrowser.m_all_tags_list.clear();
2084
2085         std::set<CopiedString>::iterator iter;
2086
2087         for ( iter = textureBrowser.m_all_tags.begin(); iter != textureBrowser.m_all_tags.end(); ++iter )
2088         {
2089                 textureBrowser.m_all_tags_list.append(TAG_COLUMN, (*iter).c_str());
2090         }
2091 }
2092
2093 void TextureBrowser_searchTags(){
2094         GSList* selected = NULL;
2095         GSList* node;
2096         gchar* tag;
2097         char buffer[256];
2098         char tags_searched[256];
2099         TextureBrowser &textureBrowser = GlobalTextureBrowser();
2100
2101         auto selection = gtk_tree_view_get_selection(textureBrowser.m_treeViewTags );
2102
2103         gtk_tree_selection_selected_foreach( selection, (GtkTreeSelectionForeachFunc)TextureBrowser_tagMoveHelper, &selected );
2104
2105         if ( selected != NULL ) {
2106                 strcpy( buffer, "/root/*/*[tag='" );
2107                 strcpy( tags_searched, "[TAGS] " );
2108
2109                 for ( node = selected; node != NULL; node = node->next )
2110                 {
2111             auto path = gtk_tree_row_reference_get_path( (GtkTreeRowReference*)node->data );
2112
2113                         if ( path ) {
2114                                 GtkTreeIter iter;
2115
2116                                 if ( gtk_tree_model_get_iter(textureBrowser.m_all_tags_list, &iter, path ) ) {
2117                                         gtk_tree_model_get(textureBrowser.m_all_tags_list, &iter, TAG_COLUMN, &tag, -1 );
2118
2119                                         strcat( buffer, tag );
2120                                         strcat( tags_searched, tag );
2121                                         if ( node != g_slist_last( node ) ) {
2122                                                 strcat( buffer, "' and tag='" );
2123                                                 strcat( tags_searched, ", " );
2124                                         }
2125                                 }
2126                         }
2127                 }
2128
2129                 strcat( buffer, "']" );
2130
2131                 g_slist_foreach( selected, (GFunc)gtk_tree_row_reference_free, NULL );
2132
2133                 textureBrowser.m_found_shaders.clear(); // delete old list
2134                 TagBuilder.TagSearch( buffer, textureBrowser.m_found_shaders );
2135
2136                 if ( !textureBrowser.m_found_shaders.empty() ) { // found something
2137                         size_t shaders_found = textureBrowser.m_found_shaders.size();
2138
2139                         globalOutputStream() << "Found " << (unsigned int)shaders_found << " textures and shaders with " << tags_searched << "\n";
2140                         ScopeDisableScreenUpdates disableScreenUpdates( "Searching...", "Loading Textures" );
2141
2142                         std::set<CopiedString>::iterator iter;
2143
2144                         for ( iter = textureBrowser.m_found_shaders.begin(); iter != textureBrowser.m_found_shaders.end(); iter++ )
2145                         {
2146                                 std::string path = ( *iter ).c_str();
2147                                 size_t pos = path.find_last_of( "/", path.size() );
2148                                 std::string name = path.substr( pos + 1, path.size() );
2149                                 path = path.substr( 0, pos + 1 );
2150                                 TextureDirectory_loadTexture( path.c_str(), name.c_str() );
2151                         }
2152                 }
2153                 textureBrowser.m_searchedTags = true;
2154                 g_TextureBrowser_currentDirectory = tags_searched;
2155
2156                 textureBrowser.m_nTotalHeight = 0;
2157                 TextureBrowser_setOriginY( textureBrowser, 0 );
2158                 TextureBrowser_heightChanged( textureBrowser );
2159                 TextureBrowser_updateTitle();
2160         }
2161         g_slist_free( selected );
2162 }
2163
2164 void TextureBrowser_toggleSearchButton(){
2165         TextureBrowser &textureBrowser = GlobalTextureBrowser();
2166         gint page = gtk_notebook_get_current_page( GTK_NOTEBOOK( textureBrowser.m_tag_notebook ) );
2167
2168         if ( page == 0 ) { // tag page
2169                 gtk_widget_show_all( textureBrowser.m_search_button );
2170         }
2171         else {
2172                 textureBrowser.m_search_button.hide();
2173         }
2174 }
2175
2176 void TextureBrowser_constructTagNotebook(){
2177         TextureBrowser &textureBrowser = GlobalTextureBrowser();
2178         textureBrowser.m_tag_notebook = ui::Widget::from(gtk_notebook_new());
2179         ui::Widget labelTags = ui::Label( "Tags" );
2180         ui::Widget labelTextures = ui::Label( "Textures" );
2181
2182         gtk_notebook_append_page( GTK_NOTEBOOK( textureBrowser.m_tag_notebook ), textureBrowser.m_scr_win_tree, labelTextures );
2183         gtk_notebook_append_page( GTK_NOTEBOOK( textureBrowser.m_tag_notebook ), textureBrowser.m_scr_win_tags, labelTags );
2184
2185         textureBrowser.m_tag_notebook.connect( "switch-page", G_CALLBACK( TextureBrowser_toggleSearchButton ), NULL );
2186
2187         gtk_widget_show_all( textureBrowser.m_tag_notebook );
2188 }
2189
2190 void TextureBrowser_constructSearchButton(){
2191         auto image = ui::Widget::from(gtk_image_new_from_stock( GTK_STOCK_FIND, GTK_ICON_SIZE_SMALL_TOOLBAR ));
2192         TextureBrowser &textureBrowser = GlobalTextureBrowser();
2193         textureBrowser.m_search_button = ui::Button(ui::New);
2194         textureBrowser.m_search_button.connect( "clicked", G_CALLBACK( TextureBrowser_searchTags ), NULL );
2195         gtk_widget_set_tooltip_text(textureBrowser.m_search_button, "Search with selected tags");
2196         textureBrowser.m_search_button.add(image);
2197 }
2198
2199 void TextureBrowser_checkTagFile(){
2200         const char SHADERTAG_FILE[] = "shadertags.xml";
2201         CopiedString default_filename, rc_filename;
2202         StringOutputStream stream( 256 );
2203         TextureBrowser &textureBrowser = GlobalTextureBrowser();
2204
2205         stream << LocalRcPath_get();
2206         stream << SHADERTAG_FILE;
2207         rc_filename = stream.c_str();
2208
2209         if ( file_exists( rc_filename.c_str() ) ) {
2210                 textureBrowser.m_tags = TagBuilder.OpenXmlDoc( rc_filename.c_str() );
2211
2212                 if ( textureBrowser.m_tags ) {
2213                         globalOutputStream() << "Loading tag file " << rc_filename.c_str() << ".\n";
2214                 }
2215         }
2216         else
2217         {
2218                 // load default tagfile
2219                 stream.clear();
2220                 stream << g_pGameDescription->mGameToolsPath.c_str();
2221                 stream << SHADERTAG_FILE;
2222                 default_filename = stream.c_str();
2223
2224                 if ( file_exists( default_filename.c_str() ) ) {
2225                         textureBrowser.m_tags = TagBuilder.OpenXmlDoc( default_filename.c_str(), rc_filename.c_str() );
2226
2227                         if ( textureBrowser.m_tags ) {
2228                                 globalOutputStream() << "Loading default tag file " << default_filename.c_str() << ".\n";
2229                         }
2230                 }
2231                 else
2232                 {
2233                         globalErrorStream() << "Unable to find default tag file " << default_filename.c_str() << ". No tag support.\n";
2234                 }
2235         }
2236 }
2237
2238 void TextureBrowser_SetNotex(){
2239         IShader* notex = QERApp_Shader_ForName( DEFAULT_NOTEX_NAME );
2240         IShader* shadernotex = QERApp_Shader_ForName( DEFAULT_SHADERNOTEX_NAME );
2241
2242         g_notex = notex->getTexture()->name;
2243
2244         g_shadernotex = shadernotex->getTexture()->name;
2245
2246         notex->DecRef();
2247         shadernotex->DecRef();
2248 }
2249
2250 static bool isGLWidgetConstructed = false;
2251 static bool isWindowConstructed = false;
2252
2253 void TextureBrowser_constructGLWidget(){
2254         TextureBrowser &textureBrowser = GlobalTextureBrowser();
2255         textureBrowser.m_gl_widget = glwidget_new( FALSE );
2256         g_object_ref( textureBrowser.m_gl_widget._handle );
2257
2258         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 );
2259         gtk_widget_set_can_focus( textureBrowser.m_gl_widget, true );
2260
2261         textureBrowser.m_sizeHandler = textureBrowser.m_gl_widget.connect( "size_allocate", G_CALLBACK( TextureBrowser_size_allocate ), &textureBrowser );
2262         textureBrowser.m_exposeHandler = textureBrowser.m_gl_widget.on_render( G_CALLBACK( TextureBrowser_expose ), &textureBrowser );
2263
2264         textureBrowser.m_gl_widget.connect( "button_press_event", G_CALLBACK( TextureBrowser_button_press ), &textureBrowser );
2265         textureBrowser.m_gl_widget.connect( "button_release_event", G_CALLBACK( TextureBrowser_button_release ), &textureBrowser );
2266         textureBrowser.m_gl_widget.connect( "motion_notify_event", G_CALLBACK( TextureBrowser_motion ), &textureBrowser );
2267         textureBrowser.m_gl_widget.connect( "scroll_event", G_CALLBACK( TextureBrowser_scroll ), &textureBrowser );
2268
2269 #ifdef WORKAROUND_MACOS_GTK2_GLWIDGET
2270         textureBrowser.m_hframe.pack_start( textureBrowser.m_gl_widget, TRUE, TRUE, 0 );
2271 #else // !WORKAROUND_MACOS_GTK2_GLWIDGET
2272         textureBrowser.m_frame.pack_start( textureBrowser.m_gl_widget, TRUE, TRUE, 0 );
2273 #endif // !WORKAROUND_MACOS_GTK2_GLWIDGET
2274
2275         textureBrowser.m_gl_widget.show();
2276
2277         isGLWidgetConstructed = true;
2278 }
2279
2280 ui::Widget TextureBrowser_constructWindow( ui::Window toplevel ){
2281         // The gl_widget and the tag assignment frame should be packed into a GtkVPaned with the slider
2282         // position stored in local.pref. gtk_paned_get_position() and gtk_paned_set_position() don't
2283         // seem to work in gtk 2.4 and the arrow buttons don't handle GTK_FILL, so here's another thing
2284         // for the "once-the-gtk-libs-are-updated-TODO-list" :x
2285         TextureBrowser &textureBrowser = GlobalTextureBrowser();
2286
2287         TextureBrowser_checkTagFile();
2288         TextureBrowser_SetNotex();
2289
2290         GlobalShaderSystem().setActiveShadersChangedNotify( ReferenceCaller<TextureBrowser, void(), TextureBrowser_activeShadersChanged>( textureBrowser ) );
2291
2292         textureBrowser.m_parent = toplevel;
2293
2294         auto table = ui::Table(3, 3, FALSE);
2295         auto vbox = ui::VBox(FALSE, 0);
2296         table.attach(vbox, {0, 1, 1, 3}, {GTK_FILL, GTK_FILL});
2297         vbox.show();
2298
2299         // ui::Widget menu_bar{ui::null};
2300         auto toolbar = ui::Toolbar::from( gtk_toolbar_new() );
2301
2302         { // menu bar
2303                 // menu_bar = ui::Widget::from(gtk_menu_bar_new());
2304                 auto menu_view = ui::Menu(ui::New);
2305                 // auto view_item = TextureBrowser_constructViewMenu( menu_view );
2306                 TextureBrowser_constructViewMenu( menu_view );
2307                 gtk_menu_set_title( menu_view, "View" );
2308                 // gtk_menu_item_set_submenu( GTK_MENU_ITEM( view_item ), menu_view );
2309                 // gtk_menu_shell_append( GTK_MENU_SHELL( menu_bar ), view_item );
2310
2311                 //gtk_table_attach( GTK_TABLE( table ), GTK_WIDGET( toolbar ), 0, 1, 0, 1, GTK_FILL, GTK_FILL, 0, 0 );
2312                 gtk_box_pack_start( GTK_BOX( vbox ), GTK_WIDGET( toolbar ), FALSE, FALSE, 0 );
2313
2314                 //view menu button
2315                 {
2316                         auto button = toolbar_append_button( toolbar, "View", "texbro_view.png" );
2317                         button.dimensions( 22, 22 );
2318                         button.connect( "clicked", G_CALLBACK( Popup_View_Menu ), menu_view );
2319
2320                         //to show detached menu over floating tex bro
2321                         gtk_menu_attach_to_widget( GTK_MENU( menu_view ), GTK_WIDGET( button ), NULL );
2322                 }
2323                 {
2324                         auto button = toolbar_append_button( toolbar, "Find / Replace...", "texbro_gtk-find-and-replace.png", "FindReplaceTextures" );
2325                         button.dimensions( 22, 22 );
2326                 }
2327                 {
2328                         auto button = toolbar_append_button( toolbar, "Flush & Reload Shaders", "texbro_refresh.png", "RefreshShaders" );
2329                         button.dimensions( 22, 22 );
2330                 }
2331                 toolbar.show();
2332
2333 /*
2334                 auto menu_tools = ui::Menu(ui::New);
2335                 auto tools_item = TextureBrowser_constructToolsMenu( menu_tools );
2336                 gtk_menu_item_set_submenu( GTK_MENU_ITEM( tools_item ), menu_tools );
2337                 gtk_menu_shell_append( GTK_MENU_SHELL( menu_bar ), tools_item );
2338 */
2339                 // table.attach(menu_bar, {0, 3, 0, 1}, {GTK_FILL, GTK_SHRINK});
2340                 // menu_bar.show();
2341         }
2342         { // Texture TreeView
2343                 textureBrowser.m_scr_win_tree = ui::ScrolledWindow(ui::New);
2344                 gtk_container_set_border_width( GTK_CONTAINER( textureBrowser.m_scr_win_tree ), 0 );
2345
2346                 // vertical only scrolling for treeview
2347                 gtk_scrolled_window_set_policy( GTK_SCROLLED_WINDOW( textureBrowser.m_scr_win_tree ), GTK_POLICY_NEVER, GTK_POLICY_ALWAYS );
2348
2349                 textureBrowser.m_scr_win_tree.show();
2350
2351                 TextureBrowser_createTreeViewTree();
2352
2353                 gtk_scrolled_window_add_with_viewport( GTK_SCROLLED_WINDOW( textureBrowser.m_scr_win_tree ), textureBrowser.m_treeViewTree  );
2354                 textureBrowser.m_treeViewTree.show();
2355         }
2356         { // gl_widget scrollbar
2357                 auto w = ui::Widget::from(gtk_vscrollbar_new( ui::Adjustment( 0,0,0,1,1,0 ) ));
2358                 table.attach(w, {2, 3, 1, 2}, {GTK_SHRINK, GTK_FILL});
2359                 w.show();
2360                 textureBrowser.m_texture_scroll = w;
2361
2362                 auto vadjustment = ui::Adjustment::from(gtk_range_get_adjustment( GTK_RANGE( textureBrowser.m_texture_scroll ) ));
2363                 vadjustment.connect( "value_changed", G_CALLBACK( TextureBrowser_verticalScroll ), &textureBrowser );
2364
2365                 textureBrowser.m_texture_scroll.visible(textureBrowser.m_showTextureScrollbar);
2366         }
2367         { // gl_widget
2368 #ifdef WORKAROUND_MACOS_GTK2_GLWIDGET
2369                 textureBrowser.m_vframe = ui::VBox( FALSE, 0 );
2370                 table.attach(textureBrowser.m_vframe, {1, 2, 1, 2});
2371
2372                 textureBrowser.m_vfiller = ui::VBox( FALSE, 0 );
2373                 textureBrowser.m_vframe.pack_start( textureBrowser.m_vfiller, FALSE, FALSE, 0 );
2374
2375                 textureBrowser.m_hframe = ui::HBox( FALSE, 0 );
2376                 textureBrowser.m_vframe.pack_start( textureBrowser.m_hframe, TRUE, TRUE, 0 );
2377
2378                 textureBrowser.m_hfiller = ui::HBox( FALSE, 0 );
2379                 textureBrowser.m_hframe.pack_start( textureBrowser.m_hfiller, FALSE, FALSE, 0 );
2380
2381                 textureBrowser.m_vframe.show();
2382                 textureBrowser.m_vfiller.show();
2383                 textureBrowser.m_hframe.show(),
2384                 textureBrowser.m_hfiller.show();
2385 #else // !WORKAROUND_MACOS_GTK2_GLWIDGET
2386                 textureBrowser.m_frame = ui::VBox( FALSE, 0 );
2387                 table.attach(textureBrowser.m_frame, {1, 2, 1, 2});
2388                 textureBrowser.m_frame.show();
2389 #endif // !WORKAROUND_MACOS_GTK2_GLWIDGET
2390
2391                 TextureBrowser_constructGLWidget();
2392         }
2393
2394         // tag stuff
2395         if ( textureBrowser.m_tags ) {
2396                 { // fill tag GtkListStore
2397                         textureBrowser.m_all_tags_list = ui::ListStore::from(gtk_list_store_new( N_COLUMNS, G_TYPE_STRING ));
2398             auto sortable = GTK_TREE_SORTABLE( textureBrowser.m_all_tags_list );
2399                         gtk_tree_sortable_set_sort_column_id( sortable, TAG_COLUMN, GTK_SORT_ASCENDING );
2400
2401                         TagBuilder.GetAllTags( textureBrowser.m_all_tags );
2402                         TextureBrowser_buildTagList();
2403                 }
2404                 { // tag menu bar
2405                         auto menu_tags = ui::Menu(ui::New);
2406                         // auto tags_item = TextureBrowser_constructTagsMenu( menu_tags );
2407                         TextureBrowser_constructTagsMenu( menu_tags );
2408                         // gtk_menu_item_set_submenu( GTK_MENU_ITEM( tags_item ), menu_tags );
2409                         // gtk_menu_shell_append( GTK_MENU_SHELL( menu_bar ), tags_item );
2410
2411                         auto button = toolbar_append_button( toolbar, "Tags", "texbro_tags.png" );
2412                         button.dimensions( 22, 22 );
2413                         button.connect( "clicked", G_CALLBACK( Popup_View_Menu ), menu_tags );
2414                 }
2415                 { // Tag TreeView
2416                         textureBrowser.m_scr_win_tags = ui::ScrolledWindow(ui::New);
2417                         gtk_container_set_border_width( GTK_CONTAINER( textureBrowser.m_scr_win_tags ), 0 );
2418
2419                         // vertical only scrolling for treeview
2420                         gtk_scrolled_window_set_policy( GTK_SCROLLED_WINDOW( textureBrowser.m_scr_win_tags ), GTK_POLICY_NEVER, GTK_POLICY_ALWAYS );
2421
2422                         TextureBrowser_createTreeViewTags();
2423
2424             auto selection = gtk_tree_view_get_selection(textureBrowser.m_treeViewTags );
2425                         gtk_tree_selection_set_mode( selection, GTK_SELECTION_MULTIPLE );
2426
2427                         gtk_scrolled_window_add_with_viewport( GTK_SCROLLED_WINDOW( textureBrowser.m_scr_win_tags ), textureBrowser.m_treeViewTags  );
2428                         textureBrowser.m_treeViewTags.show();
2429                 }
2430                 { // Texture/Tag notebook
2431                         TextureBrowser_constructTagNotebook();
2432                         vbox.pack_start( textureBrowser.m_tag_notebook, TRUE, TRUE, 0 );
2433                 }
2434                 { // Tag search button
2435                         TextureBrowser_constructSearchButton();
2436                         vbox.pack_end(textureBrowser.m_search_button, FALSE, FALSE, 0);
2437                 }
2438                 auto frame_table = ui::Table(3, 3, FALSE);
2439                 { // Tag frame
2440
2441                         textureBrowser.m_tag_frame = ui::Frame( "Tag assignment" );
2442                         gtk_frame_set_label_align( GTK_FRAME( textureBrowser.m_tag_frame ), 0.5, 0.5 );
2443                         gtk_frame_set_shadow_type( GTK_FRAME( textureBrowser.m_tag_frame ), GTK_SHADOW_NONE );
2444
2445                         table.attach(textureBrowser.m_tag_frame, {1, 3, 2, 3}, {GTK_FILL, GTK_SHRINK});
2446
2447                         frame_table.show();
2448
2449                         textureBrowser.m_tag_frame.add(frame_table);
2450                 }
2451                 { // assigned tag list
2452                         ui::Widget scrolled_win = ui::ScrolledWindow(ui::New);
2453                         gtk_container_set_border_width( GTK_CONTAINER( scrolled_win ), 0 );
2454                         gtk_scrolled_window_set_policy( GTK_SCROLLED_WINDOW( scrolled_win ), GTK_POLICY_NEVER, GTK_POLICY_ALWAYS );
2455
2456                         textureBrowser.m_assigned_store = ui::ListStore::from(gtk_list_store_new( N_COLUMNS, G_TYPE_STRING ));
2457
2458             auto sortable = GTK_TREE_SORTABLE( textureBrowser.m_assigned_store );
2459                         gtk_tree_sortable_set_sort_column_id( sortable, TAG_COLUMN, GTK_SORT_ASCENDING );
2460
2461                         auto renderer = ui::CellRendererText(ui::New);
2462
2463                         textureBrowser.m_assigned_tree = ui::TreeView(ui::TreeModel::from(textureBrowser.m_assigned_store._handle));
2464                         textureBrowser.m_assigned_store.unref();
2465                         textureBrowser.m_assigned_tree.connect( "row-activated", (GCallback) TextureBrowser_removeTags, NULL );
2466                         gtk_tree_view_set_headers_visible(textureBrowser.m_assigned_tree, FALSE );
2467
2468             auto selection = gtk_tree_view_get_selection(textureBrowser.m_assigned_tree );
2469                         gtk_tree_selection_set_mode( selection, GTK_SELECTION_MULTIPLE );
2470
2471             auto column = ui::TreeViewColumn( "", renderer, {{"text", TAG_COLUMN}} );
2472                         gtk_tree_view_append_column(textureBrowser.m_assigned_tree, column );
2473                         textureBrowser.m_assigned_tree.show();
2474
2475                         scrolled_win.show();
2476                         gtk_scrolled_window_add_with_viewport( GTK_SCROLLED_WINDOW( scrolled_win ), textureBrowser.m_assigned_tree  );
2477
2478                         frame_table.attach(scrolled_win, {0, 1, 1, 3}, {GTK_FILL, GTK_FILL});
2479                 }
2480                 { // available tag list
2481                         ui::Widget scrolled_win = ui::ScrolledWindow(ui::New);
2482                         gtk_container_set_border_width( GTK_CONTAINER( scrolled_win ), 0 );
2483                         gtk_scrolled_window_set_policy( GTK_SCROLLED_WINDOW( scrolled_win ), GTK_POLICY_NEVER, GTK_POLICY_ALWAYS );
2484
2485                         textureBrowser.m_available_store = ui::ListStore::from(gtk_list_store_new( N_COLUMNS, G_TYPE_STRING ));
2486             auto sortable = GTK_TREE_SORTABLE( textureBrowser.m_available_store );
2487                         gtk_tree_sortable_set_sort_column_id( sortable, TAG_COLUMN, GTK_SORT_ASCENDING );
2488
2489                         auto renderer = ui::CellRendererText(ui::New);
2490
2491                         textureBrowser.m_available_tree = ui::TreeView(ui::TreeModel::from(textureBrowser.m_available_store._handle));
2492                         textureBrowser.m_available_store.unref();
2493                         textureBrowser.m_available_tree.connect( "row-activated", (GCallback) TextureBrowser_assignTags, NULL );
2494                         gtk_tree_view_set_headers_visible(textureBrowser.m_available_tree, FALSE );
2495
2496             auto selection = gtk_tree_view_get_selection(textureBrowser.m_available_tree );
2497                         gtk_tree_selection_set_mode( selection, GTK_SELECTION_MULTIPLE );
2498
2499             auto column = ui::TreeViewColumn( "", renderer, {{"text", TAG_COLUMN}} );
2500                         gtk_tree_view_append_column(textureBrowser.m_available_tree, column );
2501                         textureBrowser.m_available_tree.show();
2502
2503                         scrolled_win.show();
2504                         gtk_scrolled_window_add_with_viewport( GTK_SCROLLED_WINDOW( scrolled_win ), textureBrowser.m_available_tree  );
2505
2506                         frame_table.attach(scrolled_win, {2, 3, 1, 3}, {GTK_FILL, GTK_FILL});
2507                 }
2508                 { // tag arrow buttons
2509                         auto m_btn_left = ui::Button(ui::New);
2510                         auto m_btn_right = ui::Button(ui::New);
2511                         auto m_arrow_left = ui::Widget::from(gtk_arrow_new( GTK_ARROW_LEFT, GTK_SHADOW_OUT ));
2512                         auto m_arrow_right = ui::Widget::from(gtk_arrow_new( GTK_ARROW_RIGHT, GTK_SHADOW_OUT ));
2513                         m_btn_left.add(m_arrow_left);
2514                         m_btn_right.add(m_arrow_right);
2515
2516                         // workaround. the size of the tag frame depends of the requested size of the arrow buttons.
2517                         m_arrow_left.dimensions(-1, 68);
2518                         m_arrow_right.dimensions(-1, 68);
2519
2520                         frame_table.attach(m_btn_left, {1, 2, 1, 2}, {GTK_SHRINK, GTK_EXPAND});
2521                         frame_table.attach(m_btn_right, {1, 2, 2, 3}, {GTK_SHRINK, GTK_EXPAND});
2522
2523                         m_btn_left.connect( "clicked", G_CALLBACK( TextureBrowser_assignTags ), NULL );
2524                         m_btn_right.connect( "clicked", G_CALLBACK( TextureBrowser_removeTags ), NULL );
2525
2526                         m_btn_left.show();
2527                         m_btn_right.show();
2528                         m_arrow_left.show();
2529                         m_arrow_right.show();
2530                 }
2531                 { // tag fram labels
2532                         ui::Widget m_lbl_assigned = ui::Label( "Assigned" );
2533                         ui::Widget m_lbl_unassigned = ui::Label( "Available" );
2534
2535                         frame_table.attach(m_lbl_assigned, {0, 1, 0, 1}, {GTK_EXPAND, GTK_SHRINK});
2536                         frame_table.attach(m_lbl_unassigned, {2, 3, 0, 1}, {GTK_EXPAND, GTK_SHRINK});
2537
2538                         m_lbl_assigned.show();
2539                         m_lbl_unassigned.show();
2540                 }
2541         }
2542         else { // no tag support, show the texture tree only
2543                 vbox.pack_start( textureBrowser.m_scr_win_tree, TRUE, TRUE, 0 );
2544         }
2545
2546         // TODO do we need this?
2547         //gtk_container_set_focus_chain(GTK_CONTAINER(hbox_table), NULL);
2548
2549         isWindowConstructed = true;
2550
2551         return table;
2552 }
2553
2554 void TextureBrowser_destroyGLWidget(){
2555         TextureBrowser &textureBrowser = GlobalTextureBrowser();
2556         if ( isGLWidgetConstructed )
2557         {
2558                 g_signal_handler_disconnect( G_OBJECT( textureBrowser.m_gl_widget ), textureBrowser.m_sizeHandler );
2559                 g_signal_handler_disconnect( G_OBJECT( textureBrowser.m_gl_widget ), textureBrowser.m_exposeHandler );
2560
2561 #ifdef WORKAROUND_MACOS_GTK2_GLWIDGET
2562                 textureBrowser.m_hframe.remove( textureBrowser.m_gl_widget );
2563 #else // !WORKAROUND_MACOS_GTK2_GLWIDGET
2564                 textureBrowser.m_frame.remove( textureBrowser.m_gl_widget );
2565 #endif // !WORKAROUND_MACOS_GTK2_GLWIDGET
2566
2567                 textureBrowser.m_gl_widget.unref();
2568
2569                 isGLWidgetConstructed = false;
2570         }
2571 }
2572
2573 void TextureBrowser_destroyWindow(){
2574         GlobalShaderSystem().setActiveShadersChangedNotify( Callback<void()>() );
2575
2576         TextureBrowser_destroyGLWidget();
2577 }
2578
2579 #ifdef WORKAROUND_MACOS_GTK2_GLWIDGET
2580 /* workaround for gtkglext on gtk 2 issue: OpenGL texture viewport being drawn over the other pages */
2581 /* this is very ugly: force the resizing of the viewport to a single bottom line by forcing the
2582  * resizing of the gl widget by expanding some empty boxes, so the widget area size is reduced
2583  * while covered by another page, so the texture viewport is still rendered over the other page
2584  * but does not annoy the user that much because it's just a line on the bottom that may even
2585  * be printed over existing bottom frame or very close to it. */
2586 void TextureBrowser_showGLWidget(){
2587         TextureBrowser &textureBrowser = GlobalTextureBrowser();
2588         if ( isWindowConstructed && isGLWidgetConstructed )
2589         {
2590                 textureBrowser.m_vframe.set_child_packing( textureBrowser.m_vfiller, FALSE, FALSE, 0, ui::Packing::START );
2591                 textureBrowser.m_vframe.set_child_packing( textureBrowser.m_hframe, TRUE, TRUE, 0, ui::Packing::START );
2592                 textureBrowser.m_vframe.set_child_packing( textureBrowser.m_hfiller, FALSE, FALSE, 0, ui::Packing::START );
2593                 textureBrowser.m_vframe.set_child_packing( textureBrowser.m_gl_widget, TRUE, TRUE, 0, ui::Packing::START );
2594
2595                 textureBrowser.m_gl_widget.show();
2596 }
2597 }
2598
2599 void TextureBrowser_hideGLWidget(){
2600         TextureBrowser &textureBrowser = GlobalTextureBrowser();
2601         if ( isWindowConstructed && isGLWidgetConstructed )
2602         {
2603                 textureBrowser.m_vframe.set_child_packing( textureBrowser.m_vfiller, TRUE, TRUE, 0, ui::Packing::START);
2604                 textureBrowser.m_vframe.set_child_packing( textureBrowser.m_hframe, FALSE, FALSE, 0, ui::Packing::END );
2605                 textureBrowser.m_vframe.set_child_packing( textureBrowser.m_hfiller, TRUE, TRUE, 0, ui::Packing::START);
2606                 textureBrowser.m_vframe.set_child_packing( textureBrowser.m_gl_widget, FALSE, FALSE, 0, ui::Packing::END );
2607
2608                 // The hack needs the GL widget to not be hidden to work,
2609                 // so resizing it triggers the redraw of it with the new size.
2610                 // GlobalTextureBrowser().m_gl_widget.hide();
2611
2612                 // Trigger the redraw.
2613                 TextureBrowser_redraw( &GlobalTextureBrowser() );
2614                 ui::process();
2615         }
2616 }
2617 #endif // WORKAROUND_MACOS_GTK2_GLWIDGET
2618
2619 const Vector3& TextureBrowser_getBackgroundColour( TextureBrowser& textureBrowser ){
2620         return textureBrowser.color_textureback;
2621 }
2622
2623 void TextureBrowser_setBackgroundColour( TextureBrowser& textureBrowser, const Vector3& colour ){
2624         textureBrowser.color_textureback = colour;
2625         TextureBrowser_queueDraw( textureBrowser );
2626 }
2627
2628 void TextureBrowser_selectionHelper( ui::TreeModel model, ui::TreePath path, GtkTreeIter* iter, GSList** selected ){
2629         g_assert( selected != NULL );
2630
2631         gchar* name;
2632         gtk_tree_model_get( model, iter, TAG_COLUMN, &name, -1 );
2633         *selected = g_slist_append( *selected, name );
2634 }
2635
2636 void TextureBrowser_shaderInfo(){
2637         const char* name = TextureBrowser_GetSelectedShader( GlobalTextureBrowser() );
2638         IShader* shader = QERApp_Shader_ForName( name );
2639
2640         DoShaderInfoDlg( name, shader->getShaderFileName(), "Shader Info" );
2641
2642         shader->DecRef();
2643 }
2644
2645 void TextureBrowser_addTag(){
2646         CopiedString tag;
2647         TextureBrowser &textureBrowser = GlobalTextureBrowser();
2648
2649         EMessageBoxReturn result = DoShaderTagDlg( &tag, "Add shader tag" );
2650
2651         if ( result == eIDOK && !tag.empty() ) {
2652                 GtkTreeIter iter;
2653                 textureBrowser.m_all_tags.insert( tag.c_str() );
2654                 gtk_list_store_append( textureBrowser.m_available_store, &iter );
2655                 gtk_list_store_set( textureBrowser.m_available_store, &iter, TAG_COLUMN, tag.c_str(), -1 );
2656
2657                 // Select the currently added tag in the available list
2658         auto selection = gtk_tree_view_get_selection(textureBrowser.m_available_tree );
2659                 gtk_tree_selection_select_iter( selection, &iter );
2660
2661                 textureBrowser.m_all_tags_list.append(TAG_COLUMN, tag.c_str());
2662         }
2663 }
2664
2665 void TextureBrowser_renameTag(){
2666         /* WORKAROUND: The tag treeview is set to GTK_SELECTION_MULTIPLE. Because
2667            gtk_tree_selection_get_selected() doesn't work with GTK_SELECTION_MULTIPLE,
2668            we need to count the number of selected rows first and use
2669            gtk_tree_selection_selected_foreach() then to go through the list of selected
2670            rows (which always containins a single row).
2671          */
2672
2673         GSList* selected = NULL;
2674         TextureBrowser &textureBrowser = GlobalTextureBrowser();
2675
2676         auto selection = gtk_tree_view_get_selection(textureBrowser.m_treeViewTags );
2677         gtk_tree_selection_selected_foreach( selection, GtkTreeSelectionForeachFunc( TextureBrowser_selectionHelper ), &selected );
2678
2679         if ( g_slist_length( selected ) == 1 ) { // we only rename a single tag
2680                 CopiedString newTag;
2681                 EMessageBoxReturn result = DoShaderTagDlg( &newTag, "Rename shader tag" );
2682
2683                 if ( result == eIDOK && !newTag.empty() ) {
2684                         GtkTreeIter iterList;
2685                         gchar* rowTag;
2686                         gchar* oldTag = (char*)selected->data;
2687
2688                         bool row = gtk_tree_model_get_iter_first(textureBrowser.m_all_tags_list, &iterList ) != 0;
2689
2690                         while ( row )
2691                         {
2692                                 gtk_tree_model_get(textureBrowser.m_all_tags_list, &iterList, TAG_COLUMN, &rowTag, -1 );
2693
2694                                 if ( strcmp( rowTag, oldTag ) == 0 ) {
2695                                         gtk_list_store_set( textureBrowser.m_all_tags_list, &iterList, TAG_COLUMN, newTag.c_str(), -1 );
2696                                 }
2697                                 row = gtk_tree_model_iter_next(textureBrowser.m_all_tags_list, &iterList ) != 0;
2698                         }
2699
2700                         TagBuilder.RenameShaderTag( oldTag, newTag.c_str() );
2701
2702                         textureBrowser.m_all_tags.erase( (CopiedString)oldTag );
2703                         textureBrowser.m_all_tags.insert( newTag );
2704
2705                         BuildStoreAssignedTags( textureBrowser.m_assigned_store, textureBrowser.shader.c_str(), &textureBrowser );
2706                         BuildStoreAvailableTags( textureBrowser.m_available_store, textureBrowser.m_assigned_store, textureBrowser.m_all_tags, &textureBrowser );
2707                 }
2708         }
2709         else
2710         {
2711                 ui::alert( textureBrowser.m_parent, "Select a single tag for renaming." );
2712         }
2713 }
2714
2715 void TextureBrowser_deleteTag(){
2716         GSList* selected = NULL;
2717         TextureBrowser &textureBrowser = GlobalTextureBrowser();
2718
2719         auto selection = gtk_tree_view_get_selection(textureBrowser.m_treeViewTags );
2720         gtk_tree_selection_selected_foreach( selection, GtkTreeSelectionForeachFunc( TextureBrowser_selectionHelper ), &selected );
2721
2722         if ( g_slist_length( selected ) == 1 ) { // we only delete a single tag
2723                 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 );
2724
2725                 if ( result == ui::alert_response::YES ) {
2726                         GtkTreeIter iterSelected;
2727                         gchar *rowTag;
2728
2729                         gchar* tagSelected = (char*)selected->data;
2730
2731                         bool row = gtk_tree_model_get_iter_first(textureBrowser.m_all_tags_list, &iterSelected ) != 0;
2732
2733                         while ( row )
2734                         {
2735                                 gtk_tree_model_get(textureBrowser.m_all_tags_list, &iterSelected, TAG_COLUMN, &rowTag, -1 );
2736
2737                                 if ( strcmp( rowTag, tagSelected ) == 0 ) {
2738                                         gtk_list_store_remove( textureBrowser.m_all_tags_list, &iterSelected );
2739                                         break;
2740                                 }
2741                                 row = gtk_tree_model_iter_next(textureBrowser.m_all_tags_list, &iterSelected ) != 0;
2742                         }
2743
2744                         TagBuilder.DeleteTag( tagSelected );
2745                         textureBrowser.m_all_tags.erase( (CopiedString)tagSelected );
2746
2747                         BuildStoreAssignedTags( textureBrowser.m_assigned_store, textureBrowser.shader.c_str(), &textureBrowser );
2748                         BuildStoreAvailableTags( textureBrowser.m_available_store, textureBrowser.m_assigned_store, textureBrowser.m_all_tags, &textureBrowser );
2749                 }
2750         }
2751         else {
2752                 ui::alert( textureBrowser.m_parent, "Select a single tag for deletion." );
2753         }
2754 }
2755
2756 void TextureBrowser_copyTag(){
2757         TextureBrowser &textureBrowser = GlobalTextureBrowser();
2758         textureBrowser.m_copied_tags.clear();
2759         TagBuilder.GetShaderTags( textureBrowser.shader.c_str(), textureBrowser.m_copied_tags );
2760 }
2761
2762 void TextureBrowser_pasteTag(){
2763         TextureBrowser &textureBrowser = GlobalTextureBrowser();
2764         IShader* ishader = QERApp_Shader_ForName( textureBrowser.shader.c_str() );
2765         CopiedString shader = textureBrowser.shader.c_str();
2766
2767         if ( !TagBuilder.CheckShaderTag( shader.c_str() ) ) {
2768                 CopiedString shaderFile = ishader->getShaderFileName();
2769                 if ( shaderFile.empty() ) {
2770                         // it's a texture
2771                         TagBuilder.AddShaderNode( shader.c_str(), CUSTOM, TEXTURE );
2772                 }
2773                 else
2774                 {
2775                         // it's a shader
2776                         TagBuilder.AddShaderNode( shader.c_str(), CUSTOM, SHADER );
2777                 }
2778
2779                 for ( size_t i = 0; i < textureBrowser.m_copied_tags.size(); ++i )
2780                 {
2781                         TagBuilder.AddShaderTag( shader.c_str(), textureBrowser.m_copied_tags[i].c_str(), TAG );
2782                 }
2783         }
2784         else
2785         {
2786                 for ( size_t i = 0; i < textureBrowser.m_copied_tags.size(); ++i )
2787                 {
2788                         if ( !TagBuilder.CheckShaderTag( shader.c_str(), textureBrowser.m_copied_tags[i].c_str() ) ) {
2789                                 // the tag doesn't exist - let's add it
2790                                 TagBuilder.AddShaderTag( shader.c_str(), textureBrowser.m_copied_tags[i].c_str(), TAG );
2791                         }
2792                 }
2793         }
2794
2795         ishader->DecRef();
2796
2797         TagBuilder.SaveXmlDoc();
2798         BuildStoreAssignedTags( textureBrowser.m_assigned_store, shader.c_str(), &textureBrowser );
2799         BuildStoreAvailableTags( textureBrowser.m_available_store, textureBrowser.m_assigned_store, textureBrowser.m_all_tags, &textureBrowser );
2800 }
2801
2802 void TextureBrowser_RefreshShaders(){
2803         TextureBrowser &textureBrowser = GlobalTextureBrowser();
2804
2805         /* When shaders are refreshed, forces reloading the textures as well.
2806         Previously it would at best only display shaders, at worst mess up some textured objects. */
2807
2808     auto selection = gtk_tree_view_get_selection(GlobalTextureBrowser().m_treeViewTree);
2809         GtkTreeModel* model = NULL;
2810         GtkTreeIter iter;
2811         if ( gtk_tree_selection_get_selected (selection, &model, &iter) )
2812         {
2813                 gchar dirName[1024];
2814
2815                 gchar* buffer;
2816                 gtk_tree_model_get( model, &iter, 0, &buffer, -1 );
2817                 strcpy( dirName, buffer );
2818                 g_free( buffer );
2819                 if ( !TextureBrowser_showWads() ) {
2820                         strcat( dirName, "/" );
2821                 }
2822
2823                 ScopeDisableScreenUpdates disableScreenUpdates( "Processing...", "Loading Shaders" );
2824                 GlobalShaderSystem().refresh();
2825                 /* texturebrowser tree update on vfs restart */
2826                 TextureBrowser_constructTreeStore();
2827                 UpdateAllWindows();
2828
2829                 TextureBrowser_ShowDirectory( GlobalTextureBrowser(), dirName );
2830                 TextureBrowser_queueDraw( GlobalTextureBrowser() );
2831         }
2832
2833         else{
2834                 ScopeDisableScreenUpdates disableScreenUpdates( "Processing...", "Loading Shaders" );
2835                 GlobalShaderSystem().refresh();
2836                 /* texturebrowser tree update on vfs restart */
2837                 TextureBrowser_constructTreeStore();
2838                 UpdateAllWindows();
2839         }
2840 }
2841
2842 void TextureBrowser_ToggleShowShaders(){
2843         GlobalTextureBrowser().m_showShaders ^= 1;
2844         GlobalTextureBrowser().m_showshaders_item.update();
2845
2846         GlobalTextureBrowser().m_heightChanged = true;
2847         GlobalTextureBrowser().m_originInvalid = true;
2848         g_activeShadersChangedCallbacks();
2849
2850         TextureBrowser_queueDraw( GlobalTextureBrowser() );
2851 }
2852
2853 void TextureBrowser_ToggleShowTextures(){
2854         GlobalTextureBrowser().m_showTextures ^= 1;
2855         GlobalTextureBrowser().m_showtextures_item.update();
2856
2857         GlobalTextureBrowser().m_heightChanged = true;
2858         GlobalTextureBrowser().m_originInvalid = true;
2859         g_activeShadersChangedCallbacks();
2860
2861         TextureBrowser_queueDraw( GlobalTextureBrowser() );
2862 }
2863
2864 void TextureBrowser_ToggleShowShaderListOnly(){
2865         g_TextureBrowser_shaderlistOnly ^= 1;
2866         GlobalTextureBrowser().m_showshaderlistonly_item.update();
2867
2868         TextureBrowser_constructTreeStore();
2869 }
2870
2871 void TextureBrowser_showAll(){
2872         g_TextureBrowser_currentDirectory = "";
2873         GlobalTextureBrowser().m_searchedTags = false;
2874 //      TextureBrowser_SetHideUnused( GlobalTextureBrowser(), false );
2875         TextureBrowser_ToggleHideUnused();
2876         //TextureBrowser_heightChanged( GlobalTextureBrowser() );
2877         TextureBrowser_updateTitle();
2878 }
2879
2880 void TextureBrowser_showUntagged(){
2881         TextureBrowser &textureBrowser = GlobalTextureBrowser();
2882         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 );
2883
2884         if ( result == ui::alert_response::YES ) {
2885                 textureBrowser.m_found_shaders.clear();
2886                 TagBuilder.GetUntagged( textureBrowser.m_found_shaders );
2887                 std::set<CopiedString>::iterator iter;
2888
2889                 ScopeDisableScreenUpdates disableScreenUpdates( "Searching untagged textures...", "Loading Textures" );
2890
2891                 for ( iter = textureBrowser.m_found_shaders.begin(); iter != textureBrowser.m_found_shaders.end(); iter++ )
2892                 {
2893                         std::string path = ( *iter ).c_str();
2894                         size_t pos = path.find_last_of( "/", path.size() );
2895                         std::string name = path.substr( pos + 1, path.size() );
2896                         path = path.substr( 0, pos + 1 );
2897                         TextureDirectory_loadTexture( path.c_str(), name.c_str() );
2898                         globalErrorStream() << path.c_str() << name.c_str() << "\n";
2899                 }
2900
2901                 g_TextureBrowser_currentDirectory = "Untagged";
2902                 TextureBrowser_queueDraw( GlobalTextureBrowser() );
2903                 TextureBrowser_heightChanged( textureBrowser );
2904                 TextureBrowser_updateTitle();
2905         }
2906 }
2907
2908 void TextureBrowser_FixedSize(){
2909         g_TextureBrowser_fixedSize ^= 1;
2910         GlobalTextureBrowser().m_fixedsize_item.update();
2911         TextureBrowser_activeShadersChanged( GlobalTextureBrowser() );
2912 }
2913
2914 void TextureBrowser_FilterMissing(){
2915         g_TextureBrowser_filterMissing ^= 1;
2916         GlobalTextureBrowser().m_filternotex_item.update();
2917         TextureBrowser_activeShadersChanged( GlobalTextureBrowser() );
2918         TextureBrowser_RefreshShaders();
2919 }
2920
2921 void TextureBrowser_FilterFallback(){
2922         g_TextureBrowser_filterFallback ^= 1;
2923         GlobalTextureBrowser().m_hidenotex_item.update();
2924         TextureBrowser_activeShadersChanged( GlobalTextureBrowser() );
2925         TextureBrowser_RefreshShaders();
2926 }
2927
2928 void TextureBrowser_EnableAlpha(){
2929         g_TextureBrowser_enableAlpha ^= 1;
2930         GlobalTextureBrowser().m_enablealpha_item.update();
2931         TextureBrowser_activeShadersChanged( GlobalTextureBrowser() );
2932 }
2933
2934 void TextureBrowser_exportTitle( const Callback<void(const char *)> & importer ){
2935         StringOutputStream buffer( 64 );
2936         buffer << "Textures: ";
2937         if ( !string_empty( g_TextureBrowser_currentDirectory.c_str() ) ) {
2938                 buffer << g_TextureBrowser_currentDirectory.c_str();
2939         }
2940         else
2941         {
2942                 buffer << "all";
2943         }
2944         importer( buffer.c_str() );
2945 }
2946
2947 struct TextureScale {
2948         static void Export(const TextureBrowser &self, const Callback<void(int)> &returnz) {
2949                 switch (self.m_textureScale) {
2950                         case 10:
2951                                 returnz(0);
2952                                 break;
2953                         case 25:
2954                                 returnz(1);
2955                                 break;
2956                         case 50:
2957                                 returnz(2);
2958                                 break;
2959                         case 100:
2960                                 returnz(3);
2961                                 break;
2962                         case 200:
2963                                 returnz(4);
2964                                 break;
2965                 }
2966         }
2967
2968         static void Import(TextureBrowser &self, int value) {
2969                 switch (value) {
2970                         case 0:
2971                                 TextureBrowser_setScale(self, 10);
2972                                 break;
2973                         case 1:
2974                                 TextureBrowser_setScale(self, 25);
2975                                 break;
2976                         case 2:
2977                                 TextureBrowser_setScale(self, 50);
2978                                 break;
2979                         case 3:
2980                                 TextureBrowser_setScale(self, 100);
2981                                 break;
2982                         case 4:
2983                                 TextureBrowser_setScale(self, 200);
2984                                 break;
2985                 }
2986         }
2987 };
2988
2989 struct UniformTextureSize {
2990         static void Export(const TextureBrowser &self, const Callback<void(int)> &returnz) {
2991                 returnz(GlobalTextureBrowser().m_uniformTextureSize);
2992         }
2993
2994         static void Import(TextureBrowser &self, int value) {
2995                 if (value > 16)
2996                         TextureBrowser_setUniformSize(self, value);
2997         }
2998 };
2999
3000 struct UniformTextureMinSize {
3001         static void Export(const TextureBrowser &self, const Callback<void(int)> &returnz) {
3002                 returnz(GlobalTextureBrowser().m_uniformTextureMinSize);
3003         }
3004
3005         static void Import(TextureBrowser &self, int value) {
3006                 if (value > 16)
3007                         TextureBrowser_setUniformSize(self, value);
3008         }
3009 };
3010
3011 void TextureBrowser_constructPreferences( PreferencesPage& page ){
3012         page.appendCheckBox(
3013                 "", "Texture scrollbar",
3014                 make_property<TextureBrowser_ShowScrollbar>(GlobalTextureBrowser())
3015                 );
3016         {
3017                 const char* texture_scale[] = { "10%", "25%", "50%", "100%", "200%" };
3018                 page.appendCombo(
3019                         "Texture Thumbnail Scale",
3020                         STRING_ARRAY_RANGE( texture_scale ),
3021                         make_property<TextureScale>(GlobalTextureBrowser())
3022                         );
3023         }
3024         page.appendSpinner( "Thumbnails Max Size", GlobalTextureBrowser().m_uniformTextureSize, GlobalTextureBrowser().m_uniformTextureSize, 16, 8192 );
3025         page.appendSpinner( "Thumbnails Min Size", GlobalTextureBrowser().m_uniformTextureMinSize, GlobalTextureBrowser().m_uniformTextureMinSize, 16, 8192 );
3026         page.appendEntry( "Mousewheel Increment", GlobalTextureBrowser().m_mouseWheelScrollIncrement );
3027         {
3028                 const char* startup_shaders[] = { "None", TextureBrowser_getCommonShadersName() };
3029                 page.appendCombo( "Load Shaders at Startup", reinterpret_cast<int&>( GlobalTextureBrowser().m_startupShaders ), STRING_ARRAY_RANGE( startup_shaders ) );
3030         }
3031 }
3032
3033 void TextureBrowser_constructPage( PreferenceGroup& group ){
3034         PreferencesPage page( group.createPage( "Texture Browser", "Texture Browser Preferences" ) );
3035         TextureBrowser_constructPreferences( page );
3036 }
3037
3038 void TextureBrowser_registerPreferencesPage(){
3039         PreferencesDialog_addSettingsPage( makeCallbackF(TextureBrowser_constructPage) );
3040 }
3041
3042
3043 #include "preferencesystem.h"
3044 #include "stringio.h"
3045
3046
3047 void TextureClipboard_textureSelected( const char* shader );
3048
3049 void TextureBrowser_Construct(){
3050         TextureBrowser &textureBrowser = GlobalTextureBrowser();
3051
3052         GlobalCommands_insert( "ShaderInfo", makeCallbackF(TextureBrowser_shaderInfo) );
3053         GlobalCommands_insert( "ShowUntagged", makeCallbackF(TextureBrowser_showUntagged) );
3054         GlobalCommands_insert( "AddTag", makeCallbackF(TextureBrowser_addTag) );
3055         GlobalCommands_insert( "RenameTag", makeCallbackF(TextureBrowser_renameTag) );
3056         GlobalCommands_insert( "DeleteTag", makeCallbackF(TextureBrowser_deleteTag) );
3057         GlobalCommands_insert( "CopyTag", makeCallbackF(TextureBrowser_copyTag) );
3058         GlobalCommands_insert( "PasteTag", makeCallbackF(TextureBrowser_pasteTag) );
3059         GlobalCommands_insert( "RefreshShaders", makeCallbackF(VFS_Refresh) );
3060         GlobalToggles_insert( "ShowInUse", makeCallbackF(TextureBrowser_ToggleHideUnused), ToggleItem::AddCallbackCaller( textureBrowser.m_hideunused_item ), Accelerator( 'U' ) );
3061         GlobalCommands_insert( "ShowAllTextures", makeCallbackF(TextureBrowser_showAll), Accelerator( 'A', (GdkModifierType)GDK_CONTROL_MASK ) );
3062         GlobalCommands_insert( "ToggleTextures", makeCallbackF(TextureBrowser_toggleShow), Accelerator( 'T' ) );
3063         GlobalToggles_insert( "ToggleShowShaders", makeCallbackF(TextureBrowser_ToggleShowShaders), ToggleItem::AddCallbackCaller( GlobalTextureBrowser().m_showshaders_item ) );
3064         GlobalToggles_insert( "ToggleShowTextures", makeCallbackF(TextureBrowser_ToggleShowTextures), ToggleItem::AddCallbackCaller( GlobalTextureBrowser().m_showtextures_item ) );
3065         GlobalToggles_insert( "ToggleShowShaderlistOnly", makeCallbackF(TextureBrowser_ToggleShowShaderListOnly),
3066  ToggleItem::AddCallbackCaller( GlobalTextureBrowser().m_showshaderlistonly_item ) );
3067         GlobalToggles_insert( "FixedSize", makeCallbackF(TextureBrowser_FixedSize), ToggleItem::AddCallbackCaller( GlobalTextureBrowser().m_fixedsize_item ) );
3068         GlobalToggles_insert( "FilterMissing", makeCallbackF(TextureBrowser_FilterMissing), ToggleItem::AddCallbackCaller( GlobalTextureBrowser().m_filternotex_item ) );
3069         GlobalToggles_insert( "FilterFallback", makeCallbackF(TextureBrowser_FilterFallback), ToggleItem::AddCallbackCaller( GlobalTextureBrowser().m_hidenotex_item ) );
3070         GlobalToggles_insert( "EnableAlpha", makeCallbackF(TextureBrowser_EnableAlpha), ToggleItem::AddCallbackCaller( GlobalTextureBrowser().m_enablealpha_item ) );
3071
3072         GlobalPreferenceSystem().registerPreference( "TextureScale", make_property_string<TextureScale>(textureBrowser) );
3073         GlobalPreferenceSystem().registerPreference( "UniformTextureSize", make_property_string<UniformTextureSize>(textureBrowser) );
3074         GlobalPreferenceSystem().registerPreference( "UniformTextureMinSize", make_property_string<UniformTextureMinSize>(textureBrowser) );
3075         GlobalPreferenceSystem().registerPreference( "TextureScrollbar", make_property_string<TextureBrowser_ShowScrollbar>(textureBrowser));
3076         GlobalPreferenceSystem().registerPreference( "ShowShaders", make_property_string( textureBrowser.m_showShaders ) );
3077         GlobalPreferenceSystem().registerPreference( "ShowTextures", make_property_string( GlobalTextureBrowser().m_showTextures ) );
3078         GlobalPreferenceSystem().registerPreference( "ShowShaderlistOnly", make_property_string( g_TextureBrowser_shaderlistOnly ) );
3079         GlobalPreferenceSystem().registerPreference( "FixedSize", make_property_string( g_TextureBrowser_fixedSize ) );
3080         GlobalPreferenceSystem().registerPreference( "FilterMissing", make_property_string( g_TextureBrowser_filterMissing ) );
3081         GlobalPreferenceSystem().registerPreference( "EnableAlpha", make_property_string( g_TextureBrowser_enableAlpha ) );
3082         GlobalPreferenceSystem().registerPreference( "LoadShaders", make_property_string( reinterpret_cast<int&>( textureBrowser.m_startupShaders ) ) );
3083         GlobalPreferenceSystem().registerPreference( "WheelMouseInc", make_property_string( textureBrowser.m_mouseWheelScrollIncrement ) );
3084         GlobalPreferenceSystem().registerPreference( "SI_Colors0", make_property_string( textureBrowser.color_textureback ) );
3085
3086         textureBrowser.shader = texdef_name_default();
3087
3088         Textures_setModeChangedNotify( ReferenceCaller<TextureBrowser, void(), TextureBrowser_queueDraw>( textureBrowser ) );
3089
3090         TextureBrowser_registerPreferencesPage();
3091
3092         GlobalShaderSystem().attach( g_ShadersObserver );
3093
3094         TextureBrowser_textureSelected = TextureClipboard_textureSelected;
3095 }
3096
3097 void TextureBrowser_Destroy(){
3098         GlobalShaderSystem().detach( g_ShadersObserver );
3099
3100         Textures_setModeChangedNotify( Callback<void()>() );
3101 }
3102
3103 ui::Widget TextureBrowser_getGLWidget(){
3104         return GlobalTextureBrowser().m_gl_widget;
3105 }
3106
3107 #if WORKAROUND_WINDOWS_GTK2_GLWIDGET
3108 ui::GLArea TextureBrowser_getGLWidget(){
3109         return GlobalTextureBrowser().m_gl_widget;
3110 }
3111 #endif // WORKAROUND_WINDOWS_GTK2_GLWIDGET