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