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