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