Форум программистов, компьютерный форум, киберфорум
C/С++ под Linux
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.80/5: Рейтинг темы: голосов - 5, средняя оценка - 4.80
0 / 0 / 0
Регистрация: 04.05.2017
Сообщений: 11

Реализация графического редактора через классы

21.05.2017, 16:09. Показов 994. Ответов 5
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Добрый день!

Программа реализует векторный графический редактор. При компиляции возникают ошибки. Подскажите, как исправить код

Bash
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
In file included from CWin.cpp:12:0: 
CWin.hpp: В функции-члене «virtual void CWin::SetMessageMap(int)»: 
CWin.hpp:75:15:   ошибка: parameter «ID» set but not used [-Werror=unused-but-set-parameter]  
             virtual void SetMessageMap(int ID){ID=0;}  
 
CWin.cpp: В функции «int main()»: 
CWin.cpp:324:13: ошибка: variable «rtn» set but not used [-Werror=unused-but-set-variable]         
              int rtn=0; XRectangle r; 
 
--------------------------------------------------------------------------------------------
main.cpp main.cpp:84:7: ошибка: параметр «x» не используется [-Werror=unused-parameter]   
             void OnLButtonClick(int x, int y)   
 
main.cpp:84:7: ошибка: параметр «y» не используется [-Werror=unused-parameter] 
main.cpp:224:5: ошибка: параметр «disp» не используется [-Werror=unused-parameter]  
             int Xmain(_XDisplay* disp, int scr_num)  
 
main.cpp:224:5: ошибка: параметр «scr_num» не используется [-Werror=unused-parameter]
Код программы:
CWin.hpp
Кликните здесь для просмотра всего текста

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
#ifndef __CWin_H__
#define __CWin_H__
/****** CWin.h ******/
#include <X11/X.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/Xos.h>
#include <X11/keysym.h>
#include <X11/keysymdef.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
//===================================================
extern Window win;
extern Display *Global_disp/*=NULL*/;extern int Global_ScrNum/*=0*/;
//===================================================
class CCallbackFunction
{
public:
    int id;
    int (*fun)(void);
};
 
class CSize
{
public:
    int cx, cy;
    CSize(){cx=0; cy=0;}
    CSize(int x, int y){cx = x; cy = y;}
};
 
//===================================================
 
class CWin
{
public:
    //-----------------
    Display *disp;
    int ScrNum;
    int left, top, right, bottom, border;
    int ControlNum;
    Window win;
    CWin *parent;
    Font font;
    //-----------------
    CCallbackFunction CallBackFunctions[1000];
    int NCallBackFunctions;
    //-----------------
    CWin();
    virtual ~CWin();
    int Create
        (
            int x = 0,
            int y = 0,
            int width = 200,
            int height = 100,
            int EventsMasks=ExposureMask | KeyPressMask | ButtonPressMask |
                    ButtonReleaseMask|StructureNotifyMask|PointerMotionMask,//|ResizeRedirectMask,
            int black_pixel=12345678,
            int white_pixel=12345678
        );
    int Create
        (
            CWin *parent,
            int x=0,
            int y=0,
            int width=200,
            int height=100,
            int EventsMasks=ExposureMask | KeyPressMask | ButtonPressMask |
                    ButtonReleaseMask |StructureNotifyMask|PointerMotionMask,//|ResizeRedirectMask,
            int black_pixel=12345678,
            int white_pixel=12345678
        );
    virtual void SetMessageMap(int ID){ID=0;}
    int RGB(int red, int green, int blue);//each component: 0 - 65025
    //-----------------
    void SetBackground(GC gc, int color){XSetBackground(disp,gc,color);}
    void SetForeground(GC gc, int color){XSetForeground(disp,gc,color);}
    //-----------------
    virtual void OnPaint(GC gc);
    virtual void OnSize(int cx, int cy);
    virtual void OnMove(int l, int t, int r, int b);
    virtual void OnLButtonClick(int x, int y);
    virtual void OnRButtonClick(int x, int y);
    virtual void OnCButtonClick(int x, int y);
    virtual void OnLButtonClickUp(int x, int y);
    virtual void OnRButtonClickUp(int x, int y);
    virtual void OnCButtonClickUp(int x, int y);
    virtual void OnMouseMove(int x, int y);
    virtual void OnKeyPress(char c, int ExtendedSymbol=0);
    //ExtendedSymbol: XK_Return XK_Left XK_Right XK_Down XK_Up XK_BackSpace XK_Delete
    //-----------------
    void Invalidate(int SetClear = 1);
    CSize GetTextExtent(const char *str, int l = -1);
    CSize GetTextExtent(GC gc, const char* str, int l = -1);
    //-----------------
    // virtual void OnLButtonDblClick(int x,int y);
};
//===================================================
class CButton : public CWin
{
public:
    CButton();
    int Create(CWin *parent, int left, int top, int right, int bottom, const char* Text = "Button", int id = 0);
    int Create(CWin *parent, int left, int top, const char* Text = "Button", int id = 0);
    virtual ~CButton();
    virtual void OnLButtonClick(int x,int y);
    virtual void OnLButtonClickUp(int x,int y);
    virtual void OnRButtonClick(int x,int y);
    virtual void OnCButtonClick(int x,int y);
    virtual void OnPaint(GC gc);
    virtual void SetTextColor(int clr){TextColor=clr;}
 
    char text[128];
    int IsClicked;
    int id;
    int TextColor;
};
//===================================================
int Xmain(Display *disp, int ScrNum);
//===================================================
#define SET_MESSAGE_MAP virtual void SetMessageMap(int FID);
//===================================================
#define BEGIN_MESSAGE_MAP(CMyWin) void CMyWin::SetMessageMap(int FID){
#define  ON_COMMAND(ID,OnFun)  if(ID==FID) OnFun();
#define END_MESSAGE_MAP }
//===================================================
#endif

button.cpp
Кликните здесь для просмотра всего текста

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
/****** button.cpp ******/
#include <X11/X.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/Xos.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include "CWin.hpp"
//=====================================================================
CButton::CButton() : CWin()
{
 ControlNum=1;
 text[0]='\0';
 left=top=right=bottom=0;
 parent =NULL;
 IsClicked=0;
 TextColor=RGB(0,0,0);
}
 
CButton::~CButton()
{
}
 
void CButton::OnLButtonClick(int x,int y)
{
 printf("LButton %s clicked (%d %d)\n",text,x,y);
 IsClicked=1;
 Invalidate();
 parent->SetMessageMap(id);
}
 
void CButton::OnLButtonClickUp(int x,int y)
{
 printf("LButtonU %s clicked (%d %d)\n",text,x,y);
 IsClicked=0;
 Invalidate();
}
 
void CButton::OnRButtonClick(int x,int y)
{
 printf("RButton %s clicked (%d %d)\n",text,x,y);
}
 
void CButton::OnCButtonClick(int x,int y)
{
 printf("CButton %s clicked (%d %d)\n",text,x,y);
}
 
int CButton::Create(CWin *parent,int l,int t,int r,int b,const char *s,int id)
{
 strcpy(text,s);
 this->parent=parent;
 this->left=l;
 this->right=r;
 this->top=t;
 this->bottom=b;
 this->id=id;
 
 win = XCreateSimpleWindow
      ( disp, parent->win, l, t, r-l, b-t, 0,
         BlackPixel(  disp, ScrNum),
         WhitePixel(  disp, ScrNum) );
 XSelectInput(disp,win,ExposureMask | KeyPressMask | ButtonPressMask |
            ButtonReleaseMask |StructureNotifyMask|PointerMotionMask);
//ExposureMask|KeyPressMask|ButtonPressMask|ButtonReleaseMask);
 XMapWindow(disp,win);
return 0;
}
 
int CButton::Create(CWin *parent,int l,int t,const char *s,int id)
{int r,b;
 CSize sz=parent->GetTextExtent(s);printf("extent:%d %d\n",sz.cx,sz.cy);
 r=l+5+sz.cx;
 b=t+5+sz.cy;
 strcpy(text,s);
 this->parent=parent;
 this->left=l;
 this->right=r;
 this->top=t;
 this->bottom=b;
 this->id=id;
 win = XCreateSimpleWindow
      ( disp, parent->win, l, t, r-l, b-t, 0,
         BlackPixel(  disp, ScrNum),
         WhitePixel(  disp, ScrNum) );
 XSelectInput(disp,win,ExposureMask | KeyPressMask | ButtonPressMask |
            ButtonReleaseMask |StructureNotifyMask|PointerMotionMask);
//ExposureMask|KeyPressMask|ButtonPressMask|ButtonReleaseMask);
 XMapWindow(disp,win);
return 0;
}
 
void CButton::OnPaint(GC gc)
{
 XSetForeground(disp,gc,TextColor);printf("textcolor=%d\n",TextColor);
//  SetForeground(gc,RGB(65025,0,0));
   XDrawRectangle(disp,win,gc,1,1,right-left-2,bottom-top-2);
   XDrawString(disp,win,gc,+3+(IsClicked?1:0),bottom-top-3+(IsClicked?1:0),text,strlen(text));
}
0
cpp_developer
Эксперт
20123 / 5690 / 1417
Регистрация: 09.04.2010
Сообщений: 22,546
Блог
21.05.2017, 16:09
Ответы с готовыми решениями:

Утечка памяти при реализации графического редактора
Добрый день! Программа реализует векторный графический редактор. Компилятор выдает сообщение об утечки памяти. Подскажите, как...

Использование графического редактора
как в Паскаль реализовать закрашивание какой-либо области? какими командами?

элемент графического редактора
Создать панель инструментов, добавить на нее компоненты, позво-ляющие: • выбирать тип многоугольника (треугольник, четырехугольник,...

5
0 / 0 / 0
Регистрация: 04.05.2017
Сообщений: 11
21.05.2017, 16:21  [ТС]
Продолжение сообщения

Cwin.cpp
Кликните здесь для просмотра всего текста

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
#include <X11/X.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/Xos.h>
#include <X11/keysym.h>
#include <X11/keysymdef.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include "CWin.hpp"
 
// Window win;
Display *Global_disp = NULL;
int Global_ScrNum = 0;
CWin *WinList[1000];
int NWinList = 0;
char *EventName(int n);
char FontString[]="-cronyx-times-medium-r-normal--0-0-0-0-p-0-koi8-r";
 
#define DEB 0
#define O(x) if(DEB)printf("%s\n",x);
 
CWin::CWin()
{
    ControlNum = 0;
    win = 0;
    disp = Global_disp;
    ScrNum = Global_ScrNum;
    WinList[NWinList++] = this;
    NCallBackFunctions = 0;
    font = XLoadFont(disp, FontString);
    if (font == 0)
    {
        printf("Can't load font\n");
    }
}
 
CWin::~CWin()
{
    int i;
    printf("~CWin\n");
    if (font)
    {
        XUnloadFont(disp, font);
    }
    for(i = 0; i < NWinList; i++)
    {
        if(WinList[i]==this)
        {
            for(i++;i<NWinList;i++)
            {
                WinList[i - 1] = WinList[i];
            }
            NWinList--;
        }
    }
}
 
int CWin::Create(CWin *par, int x /*=0*/, int y /*=0*/, int width /*=200*/, int height /*=100*/,
            int EventsMasks /*=ExposureMask | KeyPressMask | ButtonPressMask*/,
            int black_pixel /*=12345678*/, int white_pixel /*=12345678*/)
{
    printf("1\n");
    win = XCreateSimpleWindow
            (
                disp, par->win, x, y, width, height, 2,
                ((black_pixel == 12345678) ? BlackPixel(disp, ScrNum) : black_pixel),
                ((white_pixel == 12345678) ? WhitePixel(disp, ScrNum) : white_pixel)
            );
    border = 2;
    left = x - border;
    top = y - border;
    right = x - border + width;
    bottom = y - border + height;
    EventsMasks = EventsMasks;
    XSelectInput(disp, win, EventsMasks/*ExposureMask | KeyPressMask | ButtonPressMask*/);
    XMapWindow(disp, win);
 
    EventsMasks = EventsMasks;
 
    XResizeWindow(disp, win, right - left, bottom - top);
    XSetWindowBorderWidth(disp, win, 2);
 
    font = XLoadFont(disp, FontString);
    return 0;
}
 
int CWin::Create(int x/*=0*/,int y/*=0*/, int width/*=200*/, int height/*=100*/,
            int EventsMasks/*=ExposureMask | KeyPressMask | ButtonPressMask*/,
            int black_pixel/*=12345678*/, int white_pixel/*=12345678*/)
{
    printf("1\n");
 
    win = XCreateSimpleWindow
        (
            disp, RootWindow( disp, ScrNum), x, y, width, height, 2,
            ((black_pixel==12345678) ? BlackPixel(disp, ScrNum) : black_pixel),
            ((white_pixel==12345678) ? WhitePixel(disp, ScrNum) : white_pixel)
        );
    border = 2;
    left = x - border;
    top = y - border;
    right = x - border + width;
    bottom=y - border + height;
 
    EventsMasks = EventsMasks;
    XSelectInput(disp, win, EventsMasks);
    XMapWindow(disp, win);
    XResizeWindow(disp, win, right - left, bottom - top);
    XSetWindowBorderWidth(disp, win, 2);
 
 
    return 0;
}
 
void CWin::OnSize(int cx, int cy)
{
    printf("W OnSize:%d %d\n", cx, cy);
    XResizeWindow(disp, win, cx, cy);
    Invalidate(1);
}
 
void CWin::OnMove(int l, int t, int r, int b)
{
    printf("W OnMove:%d %d %d %d\n", l, t, r, b);
    Invalidate(0);
}
 
void CWin::OnPaint(GC  gc)
{
    unsigned int w, h;
    int x, y;
    O("OnPaint 1")
 
    x=0;
    y=0;
    w = right - left - 2 * border;
    h = bottom - top - 2 * border;
    printf("OnPaint:win=%ld x=%d y=%d w=%d h=%d right=%d left=%d border=%d\n", win, x, y, w, h, right, left, border);
    XSetForeground(disp, gc, RGB(255 * 255, 255 * 200, 255 * 200));
    XFillRectangle(disp, win, gc, x, y, w, h);
 
    O("OnPaint 5")
}
 
void CWin::OnLButtonClick(int x,int y)
{
    printf("l:x=%d y=%d\n",x,y);
}
 
void CWin::OnRButtonClick(int x,int y)
{
    printf("r:x=%d y=%d\n",x,y);
}
 
void CWin::OnCButtonClick(int x,int y)
{
    printf("c:x=%d y=%d\n",x,y);
}
 
void CWin::OnLButtonClickUp(int x,int y)
{
    printf("lu:x=%d y=%d\n",x,y);
}
 
void CWin::OnRButtonClickUp(int x,int y)
{
    printf("ru:x=%d y=%d\n",x,y);
}
 
void CWin::OnCButtonClickUp(int x,int y)
{
    printf("cu:x=%d y=%d\n",x,y);
}
 
void CWin::OnMouseMove(int x,int y)
{
    printf("move:x=%d y=%d\n",x,y);
}
 
 
void CWin::OnKeyPress(char c, int ExtendedSymbol)
{
    printf("OnKeyPress: CotrolNum=%d; c='%c' ext=%d\n",ControlNum,c,ExtendedSymbol);
    if(ExtendedSymbol==XK_Delete)printf("Delete\n");
    if(ExtendedSymbol==XK_BackSpace)printf("BackSpace\n");
    if(ExtendedSymbol==XK_Left)printf("left\n");
    if(ExtendedSymbol==XK_Right)printf("right\n");
    if(ExtendedSymbol==XK_Up)printf("up\n");
    if(ExtendedSymbol==XK_Down)printf("down\n");
}
 
void CWin::Invalidate(int SetClear)
{
    printf("Invalidate:width=%d height=%d\n",right-left,bottom-top);
    if(!SetClear)
    {
        static XEvent ev;
        int width=right-left,height=bottom-top;
        ev.xexpose.type=Expose;
        ev.xexpose.send_event=1;
        ev.xexpose.display=disp;
        ev.xexpose.window=win;
        ev.xexpose.x=ev.xexpose.y=0;ev.xexpose.width=width+1000;ev.xexpose.height=height+1000;ev.xexpose.count=0;
        XSendEvent(disp,win,1,ExposureMask,&ev);
    }
    else
    {
 
        GC gc=XCreateGC(disp,win,0,0);
        XSetBackground(disp,gc,WhitePixel(disp,ScrNum));
        XSetForeground(disp,gc,WhitePixel(disp,ScrNum));
        XFreeGC(disp,gc);
        XClearWindow(disp,win);
 
        int width=right-left,height=bottom-top;
        static XEvent ev;
        ev.xexpose.type=Expose;
        ev.xexpose.send_event=1;
        ev.xexpose.display=disp;
        ev.xexpose.window=win;
        ev.xexpose.x=ev.xexpose.y=0;ev.xexpose.width=width+1000;ev.xexpose.height=height+1000;ev.xexpose.count=0;
        XSendEvent(disp,win,1,ExposureMask,&ev);
    }
    XFlush(disp);
}
 
#include <unistd.h>
 
int main()
{
 CWin *cw;
 Window wwin;
 Display *disp;
 int ScrNum;
 
 XEvent Evnt;
 int i=0;
 
 if ( (disp = XOpenDisplay (NULL)) == NULL)
  {
    printf("\n====1");
    exit(1);
  }
 
 ScrNum = DefaultScreen( disp );
 
 Global_disp=disp; Global_ScrNum=ScrNum;
 Xmain(disp,ScrNum);
 
 while( 1 )
 {
     XNextEvent( Global_disp, &Evnt);
     printf("Event %s\n",EventName(Evnt.type));
     if(Evnt.type==UnmapNotify||Evnt.type==DestroyNotify)
     {printf("Evnt.type==UnmapNotify||Evnt.type==DestroyNotify\n");}
     for(wwin=0, cw=NULL, i=0; i < NWinList; i++)
         if (WinList[i]->win == Evnt.xany.window)
         {
             cw = WinList[i];
             wwin = Evnt.xany.window;
             break;
         }
     if(wwin==0||cw==NULL)
     {
         continue;
     }
     //---------------------------
     {
         switch (Evnt.type)
         {//Pixmap pm;
             case ButtonPress:
                 O("ButtonPress")
                     if(Evnt.xbutton.button==Button1)
                         cw->OnLButtonClick(Evnt.xbutton.x,Evnt.xbutton.y);
                 if(Evnt.xbutton.button==Button3)
                     cw->OnRButtonClick(Evnt.xbutton.x,Evnt.xbutton.y);
                 if(Evnt.xbutton.button==Button2)
                     cw->OnCButtonClick(Evnt.xbutton.x,Evnt.xbutton.y);
 
                 break;
             case ButtonRelease:
                 if(Evnt.xbutton.button==Button1)
                     cw->OnLButtonClickUp(Evnt.xbutton.x,Evnt.xbutton.y);
                 if(Evnt.xbutton.button==Button3)
                     cw->OnRButtonClickUp(Evnt.xbutton.x,Evnt.xbutton.y);
                 if(Evnt.xbutton.button==Button2)
                     cw->OnCButtonClickUp(Evnt.xbutton.x,Evnt.xbutton.y);
 
                 break;
             case MotionNotify:
                 cw->OnMouseMove(Evnt.xmotion.x,Evnt.xmotion.y);
                 break;
             case Expose:
                 O("101")
                     if ( Evnt.xexpose.count!=0 ) break;
                 GC gc; XGCValues gcv; gcv.clip_x_origin=gcv.clip_y_origin=20;
 
                 O("103")
                     gc=XCreateGC(cw->disp,cw->win,0,0);
                 if(cw->font)XSetFont(cw->disp,gc, cw->font);
                 O("105")
                 {
                     O("110")
                         cw->OnPaint(gc);
                     O("111")
                 }
 
                 for(i=0;i<NWinList;i++)
                     if(WinList[i]->parent && WinList[i]->parent==cw)
                     {
                         if(0)
                         {
                             int rtn=0; XRectangle r;
                             r.x=0;
                             r.y=0;
                             r.height=WinList[i]->bottom-WinList[i]->top;
                             r.width=WinList[i]->right-WinList[i]->left;
                             rtn=XSetClipRectangles(cw->disp,gc,WinList[i]->left,WinList[i]->top,
                                     &r,1,Unsorted);
                             gcv.clip_x_origin=gcv.clip_y_origin=0;
                         }
                         O("120")
 
                             O("125")
 
                             GC gc=XCreateGC(cw->disp,WinList[i]->win,0,0);
                         if(WinList[i]->font)XSetFont(WinList[i]->disp,gc, WinList[i]->font);
                         WinList[i]->OnPaint(gc);
                         XFreeGC(cw->disp,gc);
                     }
                 XFreeGC(cw->disp,gc);
                 O("151")
                     break;
             case ResizeRequest:
                {
                    int w, h, border = cw->border;
                    printf("ResizeRequest:win=%ld  w=%d h=%d\n", cw->win,
                             Evnt.xresizerequest.width,
                             Evnt.xresizerequest.height
                    );
                    w=Evnt.xresizerequest.width+2*border;
                    h=Evnt.xresizerequest.height+2*border;
                    cw->right=cw->left-border+w;
                    cw->bottom=cw->top-border+h;
                    cw->OnSize(Evnt.xresizerequest.width,Evnt.xresizerequest.height);
 
                }
                 break;
             case ConfigureNotify:
                 if(cw->parent==NULL)
                 {unsigned int w,h,border; int x,y;
 
                     border=Evnt.xconfigure.border_width;
                     w=Evnt.xconfigure.width+2*border;
                     h=Evnt.xconfigure.height+2*border;
                     x=Evnt.xconfigure.x;
                     y=Evnt.xconfigure.y;
                     printf("ConfigureNotify:w=%d r-l=%d border=%d\n",w,cw->right-cw->left,cw->border);
                     if((int)w==cw->right-cw->left && (int)h==cw->bottom-cw->top)
                     {
                         cw->OnMove(x,y,x+w,y+h);
                     }
                     else
                     {
                         cw->OnSize(Evnt.xconfigure.width,Evnt.xconfigure.height);
                     }
                     cw->border=border;
                     cw->left=x-border;
                     cw->top=y-border;
                     cw->right=x-border+w;
                     cw->bottom=y-border+h;
                 }
                 else
                 {
                     int border=0;border=Evnt.xconfigure.border_width;
                     printf("Subwin ConfigureNotify: w=%d r-l=%d border=%d\n",Evnt.xconfigure.width+2*border,cw->right-cw->left,cw->border);
                 }
                 for(i=0;i<NWinList;i++)
                     if(WinList[i]->parent && WinList[i]->parent==cw)
                     {
 
                     }
                 break;
             case GravityNotify:
                 cw->OnMove(Evnt.xgravity.x,Evnt.xgravity.y,0,0);
                 break;
             case KeyPress:
                 {
                     unsigned int sym=XKeycodeToKeysym(cw->disp,Evnt.xkey.keycode,0);
                     unsigned int sym_shift=XKeycodeToKeysym(cw->disp,Evnt.xkey.keycode,1);
 
                     if(Evnt.xkey.state&ShiftMask)
                     {printf("Shift l %c %c\n",sym,sym_shift);
                         if(sym_shift>=XK_a && sym_shift<=XK_z)
                             cw->OnKeyPress('a'+(sym_shift-XK_a));
                         else if(sym_shift>=XK_A && sym_shift<=XK_Z)
                             cw->OnKeyPress('A'+(sym_shift-XK_A));
                         else if(sym_shift<128)
                             cw->OnKeyPress(sym_shift);
                         else
                             cw->OnKeyPress(sym_shift,sym_shift);
                     }
                     else
                     {
#define EK(key,ch) else if(sym==key)cw->OnKeyPress(ch);
                         if(sym>=XK_a && sym<=XK_z)
                             cw->OnKeyPress('a'+(sym-XK_a));
                         else if(sym>=XK_A && sym<=XK_Z)
                             cw->OnKeyPress('A'+(sym-XK_A));
                         else if(sym>=XK_0 && sym<=XK_9)
                             cw->OnKeyPress('0'+(sym-XK_0));
                         else if(sym==XK_Return)
                             cw->OnKeyPress('\n');
                         else if(sym_shift<128)
                             cw->OnKeyPress(sym);
                         else
                             cw->OnKeyPress(sym,sym);
                     }
                 }
                 break;
             case DestroyNotify:
 
                 printf("Destroy\n");
                 break;
             case UnmapNotify:
 
                 printf("Destroy\n");
                 break;
         }
     }
 
 }
 
 XCloseDisplay( disp );
 return 0;
}
 
 
int CWin::RGB(int r,int g,int b)
{
    Colormap map=DefaultColormap(disp, ScrNum);
    XColor clr;
    clr.red=r;clr.green=g;clr.blue=b;
    clr.flags=DoRed|DoGreen|DoBlue;
 
    XAllocColor(disp,map,&clr);
    return clr.pixel;
}
 
char* EventName(int n)
{
    static char s[100];
    strcpy(s,"");
 
    if  ( n == KeyPress ) strcpy(s,"KeyPress");
    else if ( n == KeyRelease ) strcpy(s,"KeyRelease");
    else if ( n == ButtonPress ) strcpy(s,"ButtonPress");
    else if ( n == ButtonRelease ) strcpy(s,"ButtonRelease");
    else if ( n == MotionNotify ) strcpy(s,"MotionNotify");
    else if ( n == EnterNotify ) strcpy(s,"EnterNotify");
    else if ( n == LeaveNotify ) strcpy(s,"LeaveNotify");
    else if ( n == FocusIn ) strcpy(s,"FocusIn");
    else if ( n == FocusOut ) strcpy(s,"FocusOut");
    else if ( n == KeymapNotify ) strcpy(s,"KeymapNotify");
    else if ( n == Expose ) strcpy(s,"Expose");
    else if ( n == GraphicsExpose ) strcpy(s,"GraphicsExpose");
    else if ( n == NoExpose ) strcpy(s,"NoExpose");
    else if ( n == VisibilityNotify ) strcpy(s,"VisibilityNotify");
    else if ( n == CreateNotify ) strcpy(s,"CreateNotify");
    else if ( n == DestroyNotify ) strcpy(s,"DestroyNotify");
    else if ( n == UnmapNotify ) strcpy(s,"UnmapNotify");
    else if ( n == MapNotify ) strcpy(s,"MapNotify");
    else if ( n == MapRequest ) strcpy(s,"MapRequest");
    else if ( n == ReparentNotify ) strcpy(s,"ReparentNotify");
    else if ( n == ConfigureNotify ) strcpy(s,"ConfigureNotify");
    else if ( n == ConfigureRequest ) strcpy(s,"ConfigureRequest");
    else if ( n == GravityNotify ) strcpy(s,"GravityNotify");
    else if ( n == ResizeRequest ) strcpy(s,"ResizeRequest");
    else if ( n == CirculateNotify ) strcpy(s,"CirculateNotify");
    else if ( n == CirculateRequest ) strcpy(s,"CirculateRequest");
    else if ( n == PropertyNotify ) strcpy(s,"PropertyNotify");
    else if ( n == SelectionClear ) strcpy(s,"SelectionClear");
    else if ( n == SelectionRequest ) strcpy(s,"SelectionRequest");
    else if ( n == SelectionNotify ) strcpy(s,"SelectionNotify");
    else if ( n == ColormapNotify ) strcpy(s,"ColormapNotify");
    else if ( n == ClientMessage ) strcpy(s,"ClientMessage");
    else if ( n == MappingNotify ) strcpy(s,"MappingNotify");
    return s;
}
 
 
CSize CWin::GetTextExtent(GC gc, const char *str, int l)
{
    CSize sz(0,0); int direction, ascent,descent; XCharStruct overall;
    XQueryTextExtents(disp,font, str,(l>=0?l:strlen(str)), &direction, &ascent,&descent,&overall);
    gc = gc;
    str = str;
    l = l;
    return sz;
}
 
CSize CWin::GetTextExtent(const char *str, int l)
{
    CSize sz(0,0);
    int direction, ascent, descent;
    XCharStruct overall;
    GC gc;
    gc = XCreateGC(disp, win, 0, 0);
    XSetFont(disp, gc, font);
    XQueryTextExtents(disp, font, str, (l>=0?l:strlen(str)), &direction, &ascent, &descent, &overall);
    XFreeGC(disp,gc);
    sz.cx = overall.width;
    sz.cy = ascent + descent;
    gc = gc;
    str = str;
    l = l;
    return sz;
}
0
0 / 0 / 0
Регистрация: 04.05.2017
Сообщений: 11
21.05.2017, 16:31  [ТС]
Продолжение сообщения
main.cpp
Кликните здесь для просмотра всего текста

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
#include "CWin.hpp"
#include <iostream>
#include <iostream>
#include <vector>
#include <string>
#include <stdlib.h>
#include <stdio.h>
#include <fstream>
#include <sstream>
#include <math.h>
 
 
using namespace std;
 
bool lp1 = 1;
bool lp2 = 0;
 
bool del = 0;
 
vector<string> d;
string command;
string version;
 
 
class CMainWindow : public CWin
{
public:
    CMainWindow(void) : CWin(){};
    ~CMainWindow(void){};
    void OnLButtonClick(int x, int y);
    void OnPaint(GC gc)
    {
        unsigned int w, h;
        int x, y;
        x=0;
        y=0;
        w = right - left - 2 * border;
        h = bottom - top - 2 * border;
        printf("OnPaint:win=%ld x=%d y=%d w=%d h=%d right=%d left=%d border=%d\n", win, x, y, w, h, right, left, border);
        XSetForeground(disp, gc, RGB(255 * 255, 255 * 200, 255 * 200));//WhitePixel(disp,ScrNum));
        XFillRectangle(disp, win, gc, x, y, w, h);
 
        XGCValues value;
        unsigned long valuemask;
        GC gcl;
 
        value.foreground = 0;
        value.line_width = 3;
        value.fill_style = FillSolid;
        value.line_style = LineSolid;
 
        valuemask = GCLineStyle | GCLineWidth | GCFillStyle | GCForeground;
 
        gcl = XCreateGC(disp, win, valuemask, &value);
 
        unsigned int i;
        XSetForeground(disp, gc, BlackPixel(disp, ScrNum));
        XSetBackground(disp, gc, WhitePixel(disp, ScrNum));
        for (i = 0; i < d.size(); i++)
        {
            if ((d[i].size() > 4)&&(d[i].substr(0, 4) == "line"))
            {
                istringstream cur(d[i].substr(5));
                int x1, x2, y1, y2;
                cur >> x1 >> y1 >> x2 >> y2;
                XDrawLine(disp, win, gcl, x1, y1, x2, y2);
                XFlush(disp);
            }
        }
    }
    void OnSize(int cx,int cy)
    {
        Invalidate(0);
        cx=cx;
        cy=cy;
    }
};
 
class CMainButton : public CButton
{
public:
    CMainButton(void) : CButton(){};
    ~CMainButton(void)  {};
    void OnLButtonClick(int x, int y)
    {
        if (this->id == 0)
        {
            lp1 = 1;
            lp2 = 0;
            del = 0;
        }
        else if (this->id == 1)
        {
            lp1 = 0;
            lp2 = 0;
            del = 1;
        }
        else if (this->id == 2)
        {
            // extract new.pgf
            ifstream in;
            string s;
            int n;
            in.open("new.gpf");
 
            d.clear();
            in >> version;
            in >> n;
            getline(in, s);
            for (int i = 0; i <= n; i++)
            {
                getline(in, s);
                d.push_back(s);
                cout << s << endl;
                s = "";
                fflush(stdout);
            }
            in.close();
        }
        else if (this->id == 3)
        {
            // save new.pgf
            ofstream out;
            out.open("new.gpf");
            out << version << endl;
            out << d.size() << endl;
            for (unsigned int i = 0; i < d.size(); i++)
            {
                out << d[i] << endl;
            }
            out.close();
        }
    }
};
 
 
bool Belong(string line, int a, int b)
{
    istringstream out(line.substr(5));
    int x1, y1, x2, y2;
    out >> x1 >> y1 >> x2 >> y2;
    cout << x1 << endl
         << y1 << endl
         << x2 << endl
         << y2 << endl;
    cout << endl;
    cout << a << endl
         << b << endl;
    for (double t = 0; t <= 1; t += 1.0/(abs(x2 - x1) + abs(y2 - y1)))
    {
        double x = x1 + t*(x2 - x1);
        double y = y1 + t*(y2 - y1);
        if ((a - x)*(a - x) + (b - y)*(b - y) < 3)
        {
            return 1;
        }
    }
    return 0;
}
 
void CMainWindow::OnLButtonClick(int x, int y)
{
    printf("My Button Press\n");
    if (lp1 == 1)
    {
        lp1 = 0;
        lp2 = 1;
        del = 0;
        ostringstream cur;
        cur << "line ";
        cur << x << " " << y << " ";
        d.push_back(cur.str());
 
        printf("\ngot\n\n");
 
    }
    else if (lp2 == 1)
    {
        lp1 = 1;
        lp2 = 0;
        del = 0;
        ostringstream cur;
        cur << d[d.size() - 1];
        cur << x << " " << y;
        d[d.size() - 1] = cur.str();
 
        printf("\ndraw\n\n");
        GC gc; XGCValues gcv;
        gcv.clip_x_origin = gcv.clip_y_origin = 20;
        gc = XCreateGC(this->disp, this->win, 0, 0);
        if(this->font)
        {
            XSetFont(this->disp, gc, this->font);
        }
        this->OnPaint(gc);
    }
    else if (del == 1)
    {
        lp1 = 0;
        lp2 = 0;
        del = 1;
        for (unsigned int i = 0; i < d.size(); i++)
        {
            if (Belong(d[i], x, y))
            {
                d.erase(d.begin() + i);
                break;
            }
        }
 
        printf("\ndel\n\n");
        GC gc; XGCValues gcv;
        gcv.clip_x_origin = gcv.clip_y_origin = 20;
        gc = XCreateGC(this->disp, this->win, 0, 0);
        if(this->font)
        {
            XSetFont(this->disp, gc, this->font);
        }
        this->OnPaint(gc);
 
    }
}
 
int Xmain(_XDisplay* disp, int scr_num)
{
    version = "1.1";
    CMainWindow* wind1 = new CMainWindow();
    wind1->Create(0, 0, 200, 500);
    CMainButton* bline = new CMainButton();
    bline->Create(wind1, 0, 0, 50, 50, "line", 0);
    CMainButton* bdelete = new CMainButton();
    bdelete->Create(wind1, 51, 0, 50, 50, "delete", 1);
    CMainButton* bextract = new CMainButton();
    bextract->Create(wind1, 102, 0, 50, 50, "extract", 2);
    CMainButton* bsave = new CMainButton();
    bsave->Create(wind1, 153, 0, 50, 50, "save", 3);
    return 0;
}
Вложения
Тип файла: zip Graphics_editor.zip (8.4 Кб, 6 просмотров)
0
Диванный эксперт
Эксперт С++
 Аватар для Max Dark
2550 / 2064 / 971
Регистрация: 09.10.2013
Сообщений: 4,793
Записей в блоге: 4
24.05.2017, 22:52
Цитата Сообщение от Marina_271 Посмотреть сообщение
параметр «scr_num» не используется
Цитата Сообщение от Marina_271 Посмотреть сообщение
ошибка: variable «rtn» set but not used
Цитата Сообщение от Marina_271 Посмотреть сообщение
Подскажите, как исправить код
Использовать неиспользованное ) Либо удалить ненужное.
Если переменная объявлена, ведь она была объявлена не просто так?
0
153 / 148 / 66
Регистрация: 20.02.2014
Сообщений: 556
28.05.2017, 05:31
Marina_271, или убрать флаг компиляции Werror
0
0 / 0 / 0
Регистрация: 04.05.2017
Сообщений: 11
06.06.2017, 22:42  [ТС]
Ясно, спасибо!
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
raxper
Эксперт
30234 / 6612 / 1498
Регистрация: 28.12.2010
Сообщений: 21,154
Блог
06.06.2017, 22:42
Помогаю со студенческими работами здесь

Создание графического редактора
Доброго времени суток! Не знал в конкретно какую тему написать, потому что мой вопрос в принципе относится ни к одной. Есть задача:...

Написание графического редактора
Мне нужно написать на С# простенький графический редактор (на подобии пейнта). Пытался начать действовать методом тыка, а именно открывать...

Создание графического редактора
Сам я начинаю только вникать в программирование(Windows Forms c#) Суть задания (большую часть я сделал уже): Создать графический редактор,...

Разработка графического редактора
Помогите пожалста.. Разработка графического редактора.Программный модуль должен обеспечивать построение многоугольников,выбор цвета...

Доработка графического редактора
Редактор работает не так исправно, как должен. Когда вводишь текст и добавляешь угол поворота, который задается рандомно пользователем, то...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
6
Ответ Создать тему
Новые блоги и статьи
Советы по крайней бережливости. Внимание, это ОЧЕНЬ длинный пост.
Programma_Boinc 28.12.2025
Советы по крайней бережливости. Внимание, это ОЧЕНЬ длинный пост. Налог на собак: https:/ / **********/ gallery/ V06K53e Финансовый отчет в Excel: https:/ / **********/ gallery/ bKBkQFf Пост отсюда. . .
Кто-нибудь знает, где можно бесплатно получить настольный компьютер или ноутбук? США.
Programma_Boinc 26.12.2025
Нашел на реддите интересную статью под названием Anyone know where to get a free Desktop or Laptop? Ниже её машинный перевод. После долгих разбирательств я наконец-то вернула себе. . .
Thinkpad X220 Tablet — это лучший бюджетный ноутбук для учёбы, точка.
Programma_Boinc 23.12.2025
Рецензия / Мнение/ Перевод Нашел на реддите интересную статью под названием The Thinkpad X220 Tablet is the best budget school laptop period . Ниже её машинный перевод. Thinkpad X220 Tablet —. . .
PhpStorm 2025.3: WSL Terminal всегда стартует в ~
and_y87 14.12.2025
PhpStorm 2025. 3: WSL Terminal всегда стартует в ~ (home), игнорируя директорию проекта Симптом: После обновления до PhpStorm 2025. 3 встроенный терминал WSL открывается в домашней директории. . .
Как объединить две одинаковые БД Access с разными данными
VikBal 11.12.2025
Помогите пожалуйста !! Как объединить 2 одинаковые БД Access с разными данными.
Новый ноутбук
volvo 07.12.2025
Всем привет. По скидке в "черную пятницу" взял себе новый ноутбук Lenovo ThinkBook 16 G7 на Амазоне: Ryzen 5 7533HS 64 Gb DDR5 1Tb NVMe 16" Full HD Display Win11 Pro
Музыка, написанная Искусственным Интеллектом
volvo 04.12.2025
Всем привет. Некоторое время назад меня заинтересовало, что уже умеет ИИ в плане написания музыки для песен, и, собственно, исполнения этих самых песен. Стихов у нас много, уже вышли 4 книги, еще 3. . .
От async/await к виртуальным потокам в Python
IndentationError 23.11.2025
Армин Ронахер поставил под сомнение async/ await. Создатель Flask заявляет: цветные функции - провал, виртуальные потоки - решение. Не threading-динозавры, а новое поколение лёгких потоков. Откат?. . .
Поиск "дружественных имён" СОМ портов
Argus19 22.11.2025
Поиск "дружественных имён" СОМ портов На странице: https:/ / norseev. ru/ 2018/ 01/ 04/ comportlist_windows/ нашёл схожую тему. Там приведён код на С++, который показывает только имена СОМ портов, типа,. . .
Сколько Государство потратило денег на меня, обеспечивая инсулином.
Programma_Boinc 20.11.2025
Сколько Государство потратило денег на меня, обеспечивая инсулином. Вот решила сделать интересный приблизительный подсчет, сколько государство потратило на меня денег на покупку инсулинов. . . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2025, CyberForum.ru