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