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