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