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