Subversion Repositories Games.Chess Giants

Rev

Rev 1 | Rev 81 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
1 pmbaty 1
// network.cpp
2
 
3
#include "common.h"
4
 
5
 
6
// handy definitions
7
#define REACH_NEXT_FIELD_ELSE(field,action) \
8
{ \
9
   while (*(field) && !iswspace (*(field))) (field)++; if (*(field) == 0) action; \
10
   while (*(field) && iswspace (*(field))) (field)++; if (*(field) == 0) action; \
11
}
12
#define LOCATE_REPLY_END_FROM_START(end,start) \
13
{ \
14
   (end) = wcschr ((start), L'\n'); \
15
   while (((end) != NULL) && ((end)[1] == L'\\')) (end) = wcschr (&(end)[1], L'\n'); /* find the first line feed that is NOT followed by a backslash */ \
16
   if ((end) != NULL) (end)++; /* skip it */ \
17
   else (end) = (start) + wcslen (start); \
18
}
19
#define ERASE_FROM_TO(beginning,end) \
20
{ \
21
   while ((((end) != NULL) && ((beginning) < (end))) || (*(beginning) != 0)) \
22
      *(beginning) = L' ', (beginning)++; /* replace all the area with spaces */ \
23
}
24
#define IS_FIELD_PRESENT(field_var,string) \
25
   (((field_var) = wcsstr (player->recvbuffer, (string))) != NULL) /* this text is present */
26
#define IS_FIELD_PRESENT_AT_BEGINNING_OF_LINE(field_var,string) \
27
   ((((field_var) = wcsstr (player->recvbuffer, (string))) != NULL) /* this text is present... */ \
28
    && (ReachBeginningOfCurrentLine (player->recvbuffer, (field_var)) == (field_var))) /* ... at the beginning of a line */
29
 
30
 
31
 
32
// prototypes of local functions
33
static void ReadNickname (wchar_t *nickname, size_t nickname_size, wchar_t *from_string);
34
static void ReadGamename (wchar_t *gamename, size_t gamename_size, wchar_t *from_string);
35
static void ReadSpannedLine (wchar_t *outstring, size_t outstring_size, wchar_t *multiline_string);
36
 
37
 
38
void EvaluateServerReply_MOTD (player_t *player)
39
{
40
   // this function parses a network reply and evaluates it, deciding what to do
41
 
42
   // is the MOTD already filled ?
43
   if (server_motd[0] != 0)
44
      return; // if so, this reply can't be a MOTD so just return
45
 
46
   // read all received text as part of the MOTD
47
   wcscpy_s (server_motd, WCHAR_SIZEOF (server_motd), player->recvbuffer);
48
 
49
   // do we want the MOTD to be displayed ?
50
   if (options.network.want_servermessages && options.network.want_motdonconnect)
51
      Window_MOTD (); // display MOTD window if required
52
 
53
   Player_SendBuffer_Add (player, 1000, L"style 12\n"); // set the style 12 (computer-friendly board display)
54
   Player_SendBuffer_Add (player, 1000, L"who\n"); // send the players update request
55
   Player_SendBuffer_Add (player, 1000, L"sought all\n"); // send the sought games update request
56
   if (options.network.want_publicchat)
57
      Player_SendBuffer_Add (player, 1000, L"inchannel\n"); // send the chatter channels update request
58
 
59
   return; // finished evaluating the MOTD
60
}
61
 
62
 
63
void EvaluateServerReply_Announcement (player_t *player)
64
{
65
   // this function parses a network reply and evaluates it, deciding what to do
66
 
67
   // Announcement format:
68
   //RECEIVED:[
69
   //
70
   //    **ANNOUNCEMENT** from relay: FICS is relaying the 11th Delhi International
71
   //\   Open Category A 2013 - Round 3, the 24th Villa de Roquetas International 
72
   //\   Open 2013 - Round 8 and the 18th Bosnjaci International Open 2013 - Round 
73
   //\   5. To find more about Relay type "tell relay help"
74
   //]
75
 
76
   static wchar_t announcement_text[1024];
77
 
78
   wchar_t *announcement_start;
79
   wchar_t *announcement_end;
80
   wchar_t *field_start;
81
 
82
   // are both of the possible announcement headers NOT present ?
83
   if (!IS_FIELD_PRESENT (announcement_start, L"\n\n    **ANNOUNCEMENT** from ")
84
       && !IS_FIELD_PRESENT (announcement_start, L"\n\n    **UNREG ANNOUNCEMENT** from "))
85
      return; // if so, this reply can't be an announcement notification so just return
86
 
87
   // this reply is indeed an announcement ; find where it ends
88
   LOCATE_REPLY_END_FROM_START (announcement_end, announcement_start + 2);
89
 
90
   // are we concerned about server messages ?
91
   if (options.network.want_servermessages)
92
   {
93
      field_start = wcsstr (announcement_start, L": "); // reach the first colon+space, that's where the announcement starts
94
      if (field_start != NULL)
95
      {
96
         field_start += 2; // skip colon and space
97
         ReadSpannedLine (announcement_text, WCHAR_SIZEOF (announcement_text), field_start); // now format the announcement text well
98
         Scene_AddAnnouncement (&the_scene, announcement_text); // and put it in place
99
      }
100
   }
101
 
102
   // now erase the announcement from the recvbuffer, so that it cannot be misinterpreted by further parsing
103
   ERASE_FROM_TO (announcement_start, announcement_end);
104
 
105
   return; // finished evaluating this announcement
106
}
107
 
108
 
109
void EvaluateServerReply_ChannelMessage (player_t *player)
110
{
111
   // this function parses a network reply and evaluates it, deciding what to do
112
 
113
   static wchar_t channelmessage_text[1024];
114
 
115
   wchar_t nickname[32];
116
   wchar_t channelname[64];
117
   unsigned long rgbx_color;
118
   wchar_t *channelmessage_start;
119
   wchar_t *channelmessage_end;
120
   wchar_t *field_start;
121
   wchar_t *field_stop;
122
   int channel_index;
123
   int channel_number;
124
 
125
   // is the discriminatives bit for a channel message NOT present ?
126
   if (!IS_FIELD_PRESENT (field_stop, L"): "))
127
      return; // if so, this reply can't be a channel message so just return
128
 
129
   // reach beginning of current line
130
   channelmessage_start = ReachBeginningOfCurrentLine (player->recvbuffer, field_stop);
131
 
132
   // locate the first space in line (i.e. where the message text is supposed to start)
133
   field_start = wcschr (channelmessage_start, L' ');
134
   if (field_start != NULL)
135
      field_start++; // skip it
136
 
137
   // is the first space BEFORE the discirminative bit ?
138
   if (field_start < field_stop)
139
      return; // if so, this reply can't be a channel message so just return
140
 
141
   while ((field_stop > player->recvbuffer) && (*field_stop != L'('))
142
      field_stop--; // parse the string backwards to find the channel index
143
   if (*field_stop != L'(')
144
      return; // drop bogus replies
145
   channel_number = _wtoi (&field_stop[1]); // read channel number
146
   if (channel_number == 0)
147
      return; // if what's between the parentheses is not a number, this reply can't be a channel message so just return
148
 
149
   // this reply is indeed a channel message ; find where it ends
150
   LOCATE_REPLY_END_FROM_START (channelmessage_end, channelmessage_start);
151
 
152
   // are we concerned about channel messages ?
153
   if (options.network.want_publicchat)
154
   {
155
      ReadNickname (nickname, WCHAR_SIZEOF (nickname), channelmessage_start); // get the nickname
156
      ReadSpannedLine (channelmessage_text, WCHAR_SIZEOF (channelmessage_text), field_start); // get the message
157
 
158
      channel_number = _wtoi (&field_stop[1]); // and read channel number
159
      for (channel_index = 0; channel_index < chatterchannel_count; channel_index++)
160
         if (chatterchannels[channel_index].id == channel_number)
161
         {
162
            if (chatterchannels[channel_index].theme[0] != 0)
163
            {
164
               wcscpy_s (channelname, WCHAR_SIZEOF (channelname), chatterchannels[channel_index].theme);
165
               rgbx_color = chatterchannels[channel_index].color;
166
            }
167
            break; // break as soon as we find the channel's name and copy it if it exists
168
         }
169
      if (channelname[0] == 0)
170
      {
171
         swprintf_s (channelname, WCHAR_SIZEOF (channelname), L"%s %d", LOCALIZE (L"ChatterChannels_ColumnChannelNumber"), channel_number); // if it hasn't been filled, use the number
172
         rgbx_color = RGBA_TO_RGBACOLOR (17, 181, 205, 0); // default channel color
173
      }
174
 
175
      // add CC reply
176
      Scene_AddCCReply (&the_scene, nickname, channelname, rgbx_color, channelmessage_text);
177
   }
178
 
179
   // now erase the channel message from the recvbuffer, so that it cannot be misinterpreted by further parsing
180
   ERASE_FROM_TO (channelmessage_start, channelmessage_end);
181
 
182
   return; // finished evaluating this channel message
183
}
184
 
185
 
186
void EvaluateServerReply_PrivateMessage (player_t *player)
187
{
188
   // this function parses a network reply and evaluates it, deciding what to do
189
 
190
   static wchar_t privatemessage_text[16384];
191
 
192
   wchar_t nickname[32];
193
   wchar_t *privatemessage_start;
194
   wchar_t *privatemessage_end;
195
   wchar_t *field_start;
196
   wchar_t *first_space;
197
   int player_index;
198
 
199
   // is the private message discriminative bit NOT present ?
200
   // private messages have " tells you: " just after the first space
201
   if (!IS_FIELD_PRESENT (field_start, L" tells you: "))
202
      return; // if so, this reply can't be a private message so just return
203
 
204
   // look up for the last line feed and the first space of the line
205
   privatemessage_start = ReachBeginningOfCurrentLine (player->recvbuffer, field_start);
206
   first_space = wcschr (privatemessage_start, L' ');
207
 
208
   // is the first space BEFORE the discirminative bit ?
209
   if ((first_space != NULL) && (first_space < field_start))
210
      return; // if so, this reply can't be a channel message so just return
211
 
212
   // this reply is indeed a private message ; find where it ends
213
   LOCATE_REPLY_END_FROM_START (privatemessage_end, privatemessage_start + 2);
214
 
215
   ReadNickname (nickname, WCHAR_SIZEOF (nickname), privatemessage_start); // get username
216
 
217
   // is it NOT RoboAdmin OR do we care about server messages ?
218
   if ((_wcsicmp (L"ROBOadmin", nickname) != 0) || options.network.want_servermessages)
219
   {
220
      // see if this nickname exists in the list of connected players ; if not, refresh list
221
      for (player_index = 0; player_index < onlineplayer_count; player_index++)
222
         if (wcscmp (nickname, onlineplayers[player_index].nickname) == 0)
223
            break; // break as soon as we find it
224
 
225
      // have we NOT found it ?
226
      if (player_index == onlineplayer_count)
227
         Player_SendBuffer_Add (player, 1000, L"who\n"); // if so, request a players list refresh
228
 
229
      field_start += 12; // skip string break and reach the next colon, that's where the PM starts
230
      ReadSpannedLine (privatemessage_text, WCHAR_SIZEOF (privatemessage_text), field_start); // now format the PM text well
231
 
232
      // find or create our interlocutor structure and append the chat text in it
233
      Interlocutor_Chat (Interlocutor_FindOrCreate (nickname), nickname, false, privatemessage_text);
234
   }
235
 
236
   // now erase the private message from the recvbuffer, so that it cannot be misinterpreted by further parsing
237
   ERASE_FROM_TO (privatemessage_start, privatemessage_end);
238
 
239
   return; // finished evaluating this private message
240
}
241
 
242
 
243
void EvaluateServerReply_Finger (player_t *player)
244
{
245
   // this function parses a network reply and evaluates it, deciding what to do
246
 
247
   wchar_t line_buffer[256];
248
   wchar_t month_str[5];
249
   wchar_t dayhrminsec[8];
250
   wchar_t nickname[32];
251
   gamestylerating_t gs;
252
   playercard_t *playercard;
253
   player_t *local_player;
254
   wchar_t *finger_start;
255
   wchar_t *finger_end;
256
   wchar_t *field_start;
257
   wchar_t *fingerdata_start;
258
   wchar_t *string_pointer;
259
   int onlineplayer_index;
260
   int days;
261
   int hours;
262
   int minutes;
263
   int number;
264
 
265
   // is it a NEGATIVE finger reply ? "'gue$tpm' is not a valid handle."
266
   if (IS_FIELD_PRESENT (field_start, L"' is not a valid handle."))
267
   {
268
      field_start = ReachBeginningOfCurrentLine (player->recvbuffer, field_start); // look up for the last line feed
269
      if (field_start[0] == L'\'') // first character must be an apostrophe
270
      {
271
         ReadNickname (nickname, WCHAR_SIZEOF (nickname), &field_start[1]); // read username
272
 
273
         // test again with the complete finger reply header. Are we SURE it is a finger reply ?
274
         if (wcscmp (&field_start[1 + wcslen (nickname)], L"' is not a valid handle.") == 0)
275
         {
276
            // find or create our player card structure
277
            playercard = PlayerCard_FindOrCreate (nickname);
278
            playercard->doesnt_exist = true; // mark it as non-existing
279
            playercard->update_dialog = true; // and tell the dialog to update itself
280
 
281
            return; // finished evaluating this finger reply
282
         }
283
      }
284
   }
285
 
286
   // is it a NEGATIVE finger reply ? "Ambiguous name guestp:"
287
   if (IS_FIELD_PRESENT_AT_BEGINNING_OF_LINE (field_start, L"Ambiguous name "))
288
   {
289
      ReadNickname (nickname, WCHAR_SIZEOF (nickname), &field_start[15]); // read username
290
 
291
      // find or create our player card structure
292
      playercard = PlayerCard_FindOrCreate (nickname);
293
      playercard->doesnt_exist = true; // mark it as non-existing
294
      playercard->update_dialog = true; // and tell the dialog to update itself
295
 
296
      return; // finished evaluating this finger reply
297
   }
298
 
299
   // is it a NEGATIVE finger reply ? "There is no player matching the name guestpm."
300
   if (IS_FIELD_PRESENT_AT_BEGINNING_OF_LINE (field_start, L"There is no player matching the name "))
301
   {
302
      ReadNickname (nickname, WCHAR_SIZEOF (nickname), &field_start[37]); // read username
303
 
304
      // find or create our player card structure
305
      playercard = PlayerCard_FindOrCreate (nickname);
306
      playercard->doesnt_exist = true; // mark it as non-existing
307
      playercard->update_dialog = true; // and tell the dialog to update itself
308
 
309
      return; // finished evaluating this finger reply
310
   }
311
 
312
   // is it a POSITIVE finger reply ? "Finger of guestpm:"
313
   if (IS_FIELD_PRESENT_AT_BEGINNING_OF_LINE (field_start, L"Finger of "))
314
   {
315
      ReadNickname (nickname, WCHAR_SIZEOF (nickname), &field_start[10]); // get username
316
 
317
      // find or create our player card structure
318
      playercard = PlayerCard_FindOrCreate (nickname);
319
      playercard->got_reply = true; // remember it has actual data
320
 
321
      // when we have it, update username
322
      wcscpy_s (playercard->nickname, WCHAR_SIZEOF (playercard->nickname), nickname);
323
 
324
      // find local player and see whether this player card is ours
325
      local_player = Player_FindByType (PLAYER_HUMAN);
326
      if ((local_player != NULL) && (_wcsicmp (nickname, local_player->name) == 0))
327
         playercard->is_own = true; // remember this player card is ours
328
 
329
      ///////////////////////////////////////////////////////////////////////
330
      // Finger: parse the connection data (On for: n days n hours n minutes)
331
 
332
      // reach the next double line-break, that's where connection data starts
333
      fingerdata_start = wcsstr (field_start, L"\n\n");
334
      if (fingerdata_start == NULL)
335
         return; // nothing in finger reply ; reply evaluated
336
 
337
      fingerdata_start += 2; // skip them
338
      wcsgets (line_buffer, WCHAR_SIZEOF (line_buffer), fingerdata_start); // copy that line into a buffer for easy parsing
339
 
340
      // is the player currently online ?
341
      if (wcsncmp (line_buffer, L"On for: ", 8) == 0)
342
      {
343
         field_start = &line_buffer[8]; // skip the "On for: " text
344
 
345
         // according to the data presentation, read and convert in the right form
346
         if (swscanf_s (field_start, L"%d %*s %d %*s %d %*s Idle: %d %s", &days, &hours, &minutes, &number, dayhrminsec, WCHAR_SIZEOF (dayhrminsec)) == 5)
347
         {
348
            playercard->minutes_online = (days * 60 * 24) + (hours * 60) + minutes; // days, hours, minutes
349
            playercard->seconds_idle = number * (dayhrminsec[0] == L'd' ? 60 * 60 * 24 : (dayhrminsec[0] == L'h' ? 60 * 60 : (dayhrminsec[0] == L'm' ? 60 : 1)));
350
         }
351
         else if (swscanf_s (field_start, L"%d %*s %d %*s Idle: %d %s", &hours, &minutes, &number, dayhrminsec, WCHAR_SIZEOF (dayhrminsec)) == 4)
352
         {
353
            playercard->minutes_online = (hours * 60) + minutes; // hours, minutes
354
            playercard->seconds_idle = number * (dayhrminsec[0] == L'd' ? 60 * 60 * 24 : (dayhrminsec[0] == L'h' ? 60 * 60 : (dayhrminsec[0] == L'm' ? 60 : 1)));
355
         }
356
         else if (swscanf_s (field_start, L"%*d secs Idle: %d %s", &number, dayhrminsec, WCHAR_SIZEOF (dayhrminsec)) == 2)
357
         {
358
            playercard->minutes_online = 1; // less than one minute, round to 1
359
            playercard->seconds_idle = number * (dayhrminsec[0] == L'd' ? 60 * 60 * 24 : (dayhrminsec[0] == L'h' ? 60 * 60 : (dayhrminsec[0] == L'm' ? 60 : 1)));
360
         }
361
         else if (swscanf_s (field_start, L"%d %*s Idle: %d %s", &minutes, &number, dayhrminsec, WCHAR_SIZEOF (dayhrminsec)) == 3)
362
         {
363
            playercard->minutes_online = minutes; // just minutes
364
            playercard->seconds_idle = number * (dayhrminsec[0] == L'd' ? 60 * 60 * 24 : (dayhrminsec[0] == L'h' ? 60 * 60 : (dayhrminsec[0] == L'm' ? 60 : 1)));
365
         }
366
 
367
         playercard->update_dialog = true; // remember to update dialog
368
      }
369
 
370
      // else has player already disconnected ?
371
      else if (wcsncmp (line_buffer, L"Last disconnected: ", 19) == 0)
372
      {
373
         field_start = &line_buffer[19]; // skip the "Last disconnected: " text
374
 
375
         // read and convert the data in the right form
376
         if (swscanf_s (field_start, L"%*s %s %d, %*d:%*d %*s %d", month_str, WCHAR_SIZEOF (month_str), &playercard->disconnection_day, &playercard->disconnection_year) == 3)
377
            playercard->disconnection_month = MonthStringToNumber (month_str); // convert month from string to number
378
 
379
         playercard->update_dialog = true; // remember to update dialog
380
      }
381
 
382
      // else player has never connected
383
      else
384
      {
385
         playercard->disconnection_day = 0; // 0 everywhere means the player has never connected
386
         playercard->disconnection_month = 0;
387
         playercard->disconnection_year = 0;
388
 
389
         playercard->update_dialog = true; // remember to update dialog
390
      }
391
 
392
      ////////////////////////////////////////////////////////////
393
      // Finger: parse the status data (playing game N:aaa vs bbb)
394
 
395
      // see if this player is currently playing a game
396
      field_start = wcsstr (fingerdata_start, L"\n(playing game ");
397
      if (field_start != NULL)
398
      {
399
         field_start += 15; // skip the "\n(playing game " substring
400
 
401
         // update player activity in opponents list
402
         for (onlineplayer_index = 0; onlineplayer_index < onlineplayer_count; onlineplayer_index++)
403
            if (wcscmp (onlineplayers[onlineplayer_index].nickname, playercard->nickname) == 0)
404
            {
405
               // if this player is NOT involved in a tournament...
406
               if (onlineplayers[onlineplayer_index].handlestatus != HANDLESTATUS_INTOURNAMENT)
407
               {
408
                  if (playercard->seconds_idle < 5 * 60)
409
                     onlineplayers[onlineplayer_index].handlestatus = HANDLESTATUS_INGAME; // update status (playing)
410
                  else
411
                     onlineplayers[onlineplayer_index].handlestatus = HANDLESTATUS_INACTIVEORBUSY; // update status (idle)
412
               }
413
               break; // stop searching as soon as player is found
414
            }
415
 
416
         // scan the game number and name
417
         swscanf_s (field_start, L"%d: %[^)]", &playercard->game_played, playercard->game_name, WCHAR_SIZEOF (playercard->game_name));
418
         playercard->update_dialog = true; // remember to update dialog
419
      }
420
 
421
      // see if this player is currently playing a game
422
      field_start = wcsstr (fingerdata_start, L"\n(examining game ");
423
      if (field_start != NULL)
424
      {
425
         field_start += 17; // skip the "\n(examining game " substring
426
 
427
         // update player activity in opponents list
428
         for (onlineplayer_index = 0; onlineplayer_index < onlineplayer_count; onlineplayer_index++)
429
            if (wcscmp (onlineplayers[onlineplayer_index].nickname, playercard->nickname) == 0)
430
            {
431
               // if this player is NOT involved in a tournament...
432
               if (onlineplayers[onlineplayer_index].handlestatus != HANDLESTATUS_INTOURNAMENT)
433
               {
434
                  if (playercards->seconds_idle < 5 * 60)
435
                     onlineplayers[onlineplayer_index].handlestatus = HANDLESTATUS_EXAMININGAGAME; // update status (studying)
436
                  else
437
                     onlineplayers[onlineplayer_index].handlestatus = HANDLESTATUS_INACTIVEORBUSY; // update status (idle)
438
               }
439
               break; // stop searching as soon as player is found
440
            }
441
 
442
         // scan the game number and name
443
         swscanf_s (field_start, L"%d: %[^)]", &playercard->game_played, playercard->game_name, WCHAR_SIZEOF (playercard->game_name));
444
         playercard->update_dialog = true; // remember to update dialog
445
      }
446
 
447
      //////////////////////////////////////////
448
      // Finger: parse the game statistics array
449
 
450
      // see if this player has game statistics, find it and jump to the first line
451
      field_start = wcsstr (fingerdata_start, L"          rating     RD      win    loss    draw   total   best\n");
452
      if (field_start != NULL)
453
      {
454
         field_start += 64; // skip the rating table headers and its carriage return
455
 
456
         // game statistics start here. Read line per line...
457
         string_pointer = field_start; // start at the beginning of the line
458
         while ((string_pointer = wcsgets (line_buffer, WCHAR_SIZEOF (line_buffer), string_pointer)) != NULL)
459
         {
460
            if (line_buffer[0] == 0)
461
               continue; // skip empty lines
462
 
463
            memset (&gs, 0, sizeof (gs)); // reset all statistics we're about to read
464
 
465
            // does it look like a valid game statistics line ?
466
            if ((swscanf_s (line_buffer, L"%s %d %f %d %d %d %d", gs.name, WCHAR_SIZEOF (gs.name), &gs.rating, &gs.rd, &gs.win_count, &gs.loss_count, &gs.draw_count, &gs.total_matches) == 7)
467
                || (swscanf_s (line_buffer, L"%s ---- %f %d %d %d %d", gs.name, WCHAR_SIZEOF (gs.name), &gs.rd, &gs.win_count, &gs.loss_count, &gs.draw_count, &gs.total_matches) == 6))
468
            {
469
               // reallocate space to hold one game style rating more in this player card
470
               playercard->gamestyleratings = (gamestylerating_t *) SAFE_realloc (playercard->gamestyleratings, playercard->gamestylerating_count, playercard->gamestylerating_count + 1, sizeof (gamestylerating_t), false);
471
               memcpy (&playercard->gamestyleratings[playercard->gamestylerating_count], &gs, sizeof (gamestylerating_t)); // copy data
472
               playercard->gamestylerating_count++; // we know now one game style rating more for this player card
473
            }
474
         }
475
 
476
         playercard->update_dialog = true; // remember to update dialog
477
      }
478
 
479
      //////////////////////////////////////
480
      // Finger: parse the personal messages
481
 
482
      // see if this player has personal data, find it and jump to the first line
483
      field_start = wcsstr (fingerdata_start, L"\n\n 1:");
484
      if (field_start != NULL)
485
      {
486
         field_start += 2; // skip the two carriage returns
487
         finger_start = field_start;
488
 
489
         // personal data starts here. Read line per line...
490
         string_pointer = field_start; // start at the beginning of the line
491
         while ((string_pointer = wcsgets (line_buffer, WCHAR_SIZEOF (line_buffer), string_pointer)) != NULL)
492
         {
493
            if (line_buffer[0] == 0)
494
               continue; // skip empty lines
495
 
496
            // does it look like a valid personal finger data line ?
497
            if ((wcslen (line_buffer) > 4) && (wcsncmp (&line_buffer[2], L": ", 2) == 0))
498
               PlayerCard_AppendPersonalData (playercard, &line_buffer[4]); // if so, append it to player's personal data
499
            else if (wcsncmp (line_buffer, L"\\   ", 3) == 0)
500
            {
501
               if (playercard->fingertext_length > 1)
502
               {
503
                  playercard->fingertext[playercard->fingertext_length - 1] = 0; // chop off the last carriage return in finger text
504
                  playercard->fingertext_length--; // UGLY: now size no longer reflects allocated space
505
               }
506
               PlayerCard_AppendPersonalData (playercard, &line_buffer[3]); // ...and append it to player's personal data
507
            }
508
         }
509
 
510
         // now erase that text from the recvbuffer, so that it cannot be misinterpreted by further parsing
511
         LOCATE_REPLY_END_FROM_START (finger_end, finger_start);
512
         ERASE_FROM_TO (finger_start, finger_end);
513
 
514
         playercard->update_dialog = true; // remember to update dialog
515
      }
516
 
517
      return; // finished evaluating this finger reply
518
   }
519
 
520
   return; // this was not a reply we could be concerned about
521
}
522
 
523
 
524
void EvaluateServerReply_Seek (player_t *player)
525
{
526
   // this function parses a network reply and evaluates it, deciding what to do
527
 
528
   wchar_t *field_start;
529
 
530
   // are the two bits of the seek notification sentence not present ?
531
   if (!IS_FIELD_PRESENT (field_start, L") seeking ") || !IS_FIELD_PRESENT (field_start, L"\" to respond)"))
532
      return; // if so, this reply can't be a seek notification so just return
533
 
534
   // only refresh the sought games list if we're displaying it
535
   if (IsWindow (hSoughtWnd) && (lastsought_time + 5.0f < current_time))
536
      Player_SendBuffer_Add (player, 1000, L"sought all\n"); // send the sought games update request
537
 
538
   return; // finished evaluating this seek notification
539
}
540
 
541
 
542
void EvaluateServerReply_Challenge (player_t *player)
543
{
544
   // this function parses a network reply and evaluates it, deciding what to do
545
 
546
   challenge_t chal;
547
   wchar_t *field_start;
548
 
549
   // is the challenge line header NOT present ?
550
   if (!IS_FIELD_PRESENT_AT_BEGINNING_OF_LINE (field_start, L"Challenge: "))
551
      return; // if so, this reply can't be a challenge notification so just return
552
 
553
   // challenges can appear as
554
   // Challenge: IOEO (1370) pmbaty (----) unrated blitz 2 12.
555
   // Challenge: IOEO (1370) [black] pmbaty (----) unrated blitz 2 12.
556
 
557
   field_start += 11; // skip the "Challenge: " substring
558
   ReadNickname (chal.challenger, WCHAR_SIZEOF (chal.challenger), field_start); // read challenger nickname
559
   REACH_NEXT_FIELD_ELSE (field_start, return);
560
   if (*field_start == L'(')
561
      field_start++; // skip the leading parenthesis
562
   if ((*field_start != L'-') && (*field_start != L'+'))
563
      chal.challenger_level = _wtoi (field_start); // read player rating
564
   else
565
      chal.challenger_level = 0;
566
   REACH_NEXT_FIELD_ELSE (field_start, return);
567
   if (_wcsnicmp (field_start, L"[black]", 7) == 0)
568
   {
569
      chal.color = COLOR_BLACK; // opponent wants to play black
570
      REACH_NEXT_FIELD_ELSE (field_start, return);
571
   }
572
   else if (_wcsnicmp (field_start, L"[white]", 7) == 0)
573
   {
574
      chal.color = COLOR_WHITE; // opponent wants to play white
575
      REACH_NEXT_FIELD_ELSE (field_start, return);
576
   }
577
   else
578
      chal.color = COLOR_UNSPECIFIED; // opponent has no preference over which color he wants to play
579
   REACH_NEXT_FIELD_ELSE (field_start, return); // skip our name
580
   REACH_NEXT_FIELD_ELSE (field_start, return); // skip our rating   
581
   chal.is_rated = (*field_start == L'r' ? true : false); // read whether it is rated or not
582
   REACH_NEXT_FIELD_ELSE (field_start, return);
583
   ReadGamename (chal.game_type, WCHAR_SIZEOF (chal.game_type), field_start); // read game type
584
   REACH_NEXT_FIELD_ELSE (field_start, return);
585
   chal.initial_time = (float) _wtoi (field_start); // read initial time
586
   REACH_NEXT_FIELD_ELSE (field_start, return);
587
   chal.increment = (float) _wtoi (field_start); // read increment
588
 
589
   // is this variant unsupported ?
590
   if ((_wcsicmp (chal.game_type, L"Untimed") != 0) && (_wcsicmp (chal.game_type, L"Standard") != 0)
591
       && (_wcsicmp (chal.game_type, L"Blitz") != 0) && (_wcsicmp (chal.game_type, L"Lightning") != 0))
592
      Player_SendBuffer_Add (player, 1000, L"decline %s\n", chal.challenger); // automatically decline all unsupported games
593
   else
594
   {
595
      // supported variant. Display a message box for the user to choose whether to accept or decline.
596
 
597
      // request a player list update before displaying the dialog box
598
      if (lastonlineplayers_time + 5.0f < current_time)
599
         Player_SendBuffer_Add (player, 1000, L"who\n");
600
 
601
      // print a notification in this player's chat window
602
      Interlocutor_Notify (Interlocutor_FindOrCreate (chal.challenger), LOCALIZE (L"Chat_InvitationReceived"), chal.challenger);
603
 
604
      // find or create our challenge structure and update its data
605
      Challenge_UpdateData (Challenge_FindOrCreate (chal.challenger), &chal);
606
   }
607
 
608
   return; // finished evaluating this challenge notification
609
}
610
 
611
 
612
void EvaluateServerReply_ChallengeAccepted (player_t *player)
613
{
614
   // this function parses a network reply and evaluates it, deciding what to do
615
 
616
   wchar_t nickname[32];
617
   wchar_t *line_start;
618
   wchar_t *field_start;
619
   interlocutor_t *interlocutor;
620
   int player_index;
621
 
622
   // is the challenge accepted notification discriminative bit NOT present ?
623
   if (!IS_FIELD_PRESENT (field_start, L" accepts the match offer."))
624
      return; // if so, this reply can't be a challenge reply notification so just return
625
 
626
   line_start = ReachBeginningOfCurrentLine (player->recvbuffer, field_start); // look up for the last line feed
627
   ReadNickname (nickname, WCHAR_SIZEOF (nickname), line_start); // get username
628
 
629
   // see if this nickname exists in the list of connected players ; if not, refresh list
630
   for (player_index = 0; player_index < onlineplayer_count; player_index++)
631
      if (wcscmp (nickname, onlineplayers[player_index].nickname) == 0)
632
         break; // break as soon as we find it
633
 
634
   // have we NOT found it ?
635
   if (player_index == onlineplayer_count)
636
      Player_SendBuffer_Add (player, 1000, L"who\n"); // if so, request a players list refresh
637
 
638
   // send a notification to this player's chat window
639
   interlocutor = Interlocutor_FindOrCreate (nickname);
640
   Interlocutor_Notify (interlocutor, LOCALIZE (L"Chat_InvitationAcceptedByOther"), nickname);
641
   if (IsWindow (interlocutor->hWnd))
642
      ShowWindow (interlocutor->hWnd, SW_MINIMIZE); // minimize chat window immediately
643
 
644
   return; // finished evaluating this challenge reply notification
645
}
646
 
647
 
648
void EvaluateServerReply_ChallengeDeclined (player_t *player)
649
{
650
   // this function parses a network reply and evaluates it, deciding what to do
651
 
652
   wchar_t nickname[32];
653
   wchar_t *line_start;
654
   wchar_t *field_start;
655
   int player_index;
656
 
657
   // is the challenge declined notification discriminative bit NOT present ?
658
   if (!IS_FIELD_PRESENT (field_start, L" declines the match offer."))
659
      return; // if so, this reply can't be a challenge reply notification so just return
660
 
661
   line_start = ReachBeginningOfCurrentLine (player->recvbuffer, field_start); // look up for the last line feed
662
   ReadNickname (nickname, WCHAR_SIZEOF (nickname), line_start); // get username
663
 
664
   // see if this nickname exists in the list of connected players ; if not, refresh list
665
   for (player_index = 0; player_index < onlineplayer_count; player_index++)
666
      if (wcscmp (nickname, onlineplayers[player_index].nickname) == 0)
667
         break; // break as soon as we find it
668
 
669
   // have we NOT found it ?
670
   if (player_index == onlineplayer_count)
671
      Player_SendBuffer_Add (player, 1000, L"who\n"); // if so, request a players list refresh
672
 
673
   // send a notification to this player's chat window
674
   Interlocutor_Notify (Interlocutor_FindOrCreate (nickname), LOCALIZE (L"Chat_InvitationDeclinedByOther"), nickname);
675
 
676
   return; // finished evaluating this challenge reply notification
677
}
678
 
679
 
680
void EvaluateServerReply_Takeback (player_t *player)
681
{
682
   // this function parses a network reply and evaluates it, deciding what to do
683
 
684
   wchar_t *field_start;
685
   wchar_t *field_stop;
686
   int howmany_halfmoves;
687
 
688
   // is the challenge declined notification discriminative bit NOT present ?
689
   if (!IS_FIELD_PRESENT (field_start, L" would like to take back ") || !IS_FIELD_PRESENT (field_stop, L" half move(s)"))
690
      return; // if so, this reply can't be a challenge reply notification so just return
691
 
692
   // read the numbre of half moves the opponent reclaims
693
   swscanf_s (field_start, L" would like to take back %d ", &howmany_halfmoves);
694
 
695
   // send a notification to the local player's chat window
696
   Interlocutor_Notify (Interlocutor_FindOrCreate (player->name), LOCALIZE (L"Chat_TakebackRequestReceived"), player->name, howmany_halfmoves);
697
   DialogBox_Takeback (howmany_halfmoves); // and fire up a modal dialog box to ask confirmation to the local player
698
 
699
   return; // finished evaluating this challenge reply notification
700
}
701
 
702
 
703
void EvaluateServerReply_TakebackDeclinedByOther (player_t *player)
704
{
705
   // this function parses a network reply and evaluates it, deciding what to do
706
 
707
   wchar_t *field_start;
708
 
709
   // is the takeback declined notification discriminative bit NOT present ?
710
   if (!IS_FIELD_PRESENT (field_start, L" declines the takeback request."))
711
      return; // if so, this reply can't be a takeback reply notification so just return
712
 
713
   // send a notification to the local player's chat window
714
   Interlocutor_Notify (Interlocutor_FindOrCreate (player->name), LOCALIZE (L"Chat_TakebackRefused"), player->name);
715
 
716
   return; // finished evaluating this challenge reply notification
717
}
718
 
719
 
720
void EvaluateServerReply_TakebackDeclinedByYou (player_t *player)
721
{
722
   // this function parses a network reply and evaluates it, deciding what to do
723
 
724
   wchar_t *field_start;
725
 
726
   // is the takeback declined notification discriminative bit NOT present ?
727
   if (!IS_FIELD_PRESENT_AT_BEGINNING_OF_LINE (field_start, L"You decline the takeback request from "))
728
      return; // if so, this reply can't be a takeback reply notification so just return
729
 
730
   // send a notification to the local player's chat window
731
   Interlocutor_Notify (Interlocutor_FindOrCreate (player->name), LOCALIZE (L"Chat_TakebackRefused"), player->name);
732
 
733
   return; // finished evaluating this challenge reply notification
734
}
735
 
736
 
737
void EvaluateServerReply_PlayNotAllowed (player_t *player)
738
{
739
   // this function parses a network reply and evaluates it, deciding what to do
740
 
741
   wchar_t *field_start;
742
 
743
   // is the play reply notification discriminative bit NOT present ?
744
   if (!IS_FIELD_PRESENT_AT_BEGINNING_OF_LINE (field_start, L"Only registered players can play rated games."))
745
      return; // if so, this reply can't be a play reply notification so just return
746
 
747
   // display a message box for the player to know that his opponent refuses to play
748
   messagebox.hWndParent = (IsWindow (hSoughtWnd) ? hSoughtWnd : hMainWnd);
749
   wcscpy_s (messagebox.title, WCHAR_SIZEOF (messagebox.title), LOCALIZE (L"PlayReply_ServerReply"));
750
   swprintf_s (messagebox.text, WCHAR_SIZEOF (messagebox.text), LOCALIZE (L"PlayReply_OnlyRegisteredCanPlayRated"));
751
   messagebox.flags = MB_ICONINFORMATION | MB_OK;
752
   DialogBox_Message (&messagebox); // display a modeless error message box
753
 
754
   return; // finished evaluating this play reply notification
755
}
756
 
757
 
758
void EvaluateServerReply_PlayUnexistent (player_t *player)
759
{
760
   // this function parses a network reply and evaluates it, deciding what to do
761
 
762
   wchar_t *field_start;
763
 
764
   // is the play reply notification discriminative bit NOT present ?
765
   if (!IS_FIELD_PRESENT_AT_BEGINNING_OF_LINE (field_start, L"That seek is not available."))
766
      return; // if so, this reply can't be a play reply so just return
767
 
768
   // display a message box for the player to know that his opponent refuses to play
769
   messagebox.hWndParent = (IsWindow (hSoughtWnd) ? hSoughtWnd : hMainWnd);
770
   wcscpy_s (messagebox.title, WCHAR_SIZEOF (messagebox.title), LOCALIZE (L"PlayReply_ServerReply"));
771
   swprintf_s (messagebox.text, WCHAR_SIZEOF (messagebox.text), LOCALIZE (L"PlayReply_UnexistentSeek"));
772
   messagebox.flags = MB_ICONINFORMATION | MB_OK;
773
   DialogBox_Message (&messagebox); // display a modeless error message box
774
 
775
   return; // finished evaluating this play reply notification
776
}
777
 
778
 
779
void EvaluateServerReply_PlayWrongRating (player_t *player)
780
{
781
   // this function parses a network reply and evaluates it, deciding what to do
782
 
783
   wchar_t *field_start;
784
 
785
   // is the play reply notification discriminative bit NOT present ?
786
   if (!IS_FIELD_PRESENT_AT_BEGINNING_OF_LINE (field_start, L"Your rating does not qualify for this seek."))
787
      return; // if so, this reply can't be a play reply so just return
788
 
789
   // display a message box for the player to know that his opponent refuses to play
790
   messagebox.hWndParent = (IsWindow (hSoughtWnd) ? hSoughtWnd : hMainWnd);
791
   wcscpy_s (messagebox.title, WCHAR_SIZEOF (messagebox.title), LOCALIZE (L"PlayReply_ServerReply"));
792
   swprintf_s (messagebox.text, WCHAR_SIZEOF (messagebox.text), LOCALIZE (L"PlayReply_WrongRating"));
793
   messagebox.flags = MB_ICONINFORMATION | MB_OK;
794
   DialogBox_Message (&messagebox); // display a modeless error message box
795
 
796
   return; // finished evaluating this play reply notification
797
}
798
 
799
 
800
void EvaluateServerReply_ChannelsAndMembers (player_t *player)
801
{
802
   // this function parses a network reply and evaluates it, deciding what to do
803
 
804
   chatterchannel_t cc;
805
   wchar_t *field_start;
806
   wchar_t *field_stop;
807
   wchar_t *string_pointer;
808
   wchar_t *big_buffer;
809
   player_t *local_player;
810
   int previouslyselected_channelid;
811
   int naturallanguagechannel_index;
812
   int chatterchannel_index;
813
   int cctheme_length;
814
   int char_index;
815
 
816
   // is the channels and members header bit NOT present ?
817
   if (!IS_FIELD_PRESENT_AT_BEGINNING_OF_LINE (field_start, L"Channel "))
818
      return; // if so, this reply can't be a channels and members list so just return
819
 
820
   local_player = Player_FindByType (PLAYER_HUMAN); // get a pointer to the human player
821
 
822
   // is a chatter channel selected ?
823
   if (selected_chatterchannel != NULL)
824
      previouslyselected_channelid = selected_chatterchannel->id; // save its ID
825
   else
826
      previouslyselected_channelid = -1; // -1 will instruct us to select a default chatter channel
827
 
828
   // for each chatter channel we know already...
829
   for (chatterchannel_index = 0; chatterchannel_index < chatterchannel_count; chatterchannel_index++)
830
   {
831
      SAFE_free ((void **) &chatterchannels[chatterchannel_index].members); // for each channel, free its members array
832
      chatterchannels[chatterchannel_index].member_count = 0;
833
   }
834
   SAFE_free ((void **) &chatterchannels); // free the chatter channel list we know
835
   chatterchannel_count = 0; // reset the chatter channel count
836
   naturallanguagechannel_index = -1; // reset the natural language channel index
837
 
838
   // linearize the string
839
   string_pointer = field_start;
840
   while (string_pointer[1] != 0)
841
   {
842
      if ((string_pointer[0] == L'\n') && (string_pointer[1] == L'\\'))
843
         string_pointer[0] = string_pointer[1] = L' '; // replace every newline followed by a backslash by two spaces
844
      string_pointer++;
845
   }
846
 
847
   // mallocate space for a big buffer
848
   big_buffer = (wchar_t *) SAFE_malloc (1024 * 1024, sizeof (wchar_t), false);
849
 
850
   // read line per line
851
   string_pointer = ReachBeginningOfCurrentLine (player->recvbuffer, field_start); // start at the first character
852
   while ((string_pointer = wcsgets (big_buffer, 1024 * 1024, string_pointer)) != NULL)
853
   {
854
      if (big_buffer[0] == 0)
855
         break; // if it's an empty line, then the channel list is finished
856
 
857
      // now parse the chatter channel data
858
      field_start = big_buffer;
859
      memset (&cc, 0, sizeof (cc));
860
 
861
      REACH_NEXT_FIELD_ELSE (field_start, continue);
862
      cc.id = _wtoi (field_start); // read chatter channel id
863
 
864
      REACH_NEXT_FIELD_ELSE (field_start, continue);
865
      if (*field_start == L'"')
866
      {
867
         field_start++; // skip the quote
868
         field_stop = field_start;
869
         while (*field_stop && (*field_stop != L'"'))
870
            field_stop++; // reach the next quote
871
         if (*field_stop == 0)
872
            continue; // discard bogus lines
873
         *field_stop = 0; // break the string here
874
         wcscpy_s (cc.theme, WCHAR_SIZEOF (cc.theme), field_start); // copy theme
875
         cctheme_length = wcslen (cc.theme);
876
         for (char_index = 0; char_index < cctheme_length; char_index++)
877
            if (cc.theme[char_index] == L'_')
878
               cc.theme[char_index] = L' '; // convert underscores to spaces
59 pmbaty 879
         if (_wcsicmp (cc.theme, languages[language_id].name) == 0)
1 pmbaty 880
            naturallanguagechannel_index = chatterchannel_count; // if this channel is the natural language one, remember it
881
         field_start = field_stop + 1; // and continue reading the string
882
         REACH_NEXT_FIELD_ELSE (field_start, continue);
883
      }
884
 
885
      // determine the channel color according to channel ID
886
      srand (1000 + cc.id);
887
      cc.color = RGBA_TO_RGBACOLOR (rand () % 256, rand () % 256, rand () % 256, 0xff);
888
 
889
      // now read the channel members
890
      cc.members = NULL;
891
      cc.member_count = 0;
892
      while (*field_start != 0)
893
      {
894
         cc.members = (chatterchannelmember_t *) SAFE_realloc (cc.members, cc.member_count, cc.member_count + 1, sizeof (chatterchannelmember_t), false);
895
         if (*field_start == '{')
896
         {
897
            ReadNickname (cc.members[cc.member_count].nickname, WCHAR_SIZEOF (cc.members[cc.member_count].nickname), &field_start[1]);
898
            cc.members[cc.member_count].is_silenced = true; // this player plays in silence
899
         }
900
         else
901
         {
902
            ReadNickname (cc.members[cc.member_count].nickname, WCHAR_SIZEOF (cc.members[cc.member_count].nickname), field_start);
903
            cc.members[cc.member_count].is_silenced = false; // this player allows us to talk to him
904
         }
905
         if (wcscmp (cc.members[cc.member_count].nickname, local_player->name) == 0)
906
            cc.is_open = true; // if we are on this channel, mark this channel as open
907
         cc.member_count++; // reallocate, read player nickname and increase chatter channel members array size
908
         REACH_NEXT_FIELD_ELSE (field_start, continue); // and advance one player more
909
      }
910
 
911
      // all parsing was OK, reallocate chatter channels list to have one channel more
912
      chatterchannels = (chatterchannel_t *) SAFE_realloc (chatterchannels, chatterchannel_count, chatterchannel_count + 1, sizeof (chatterchannel_t), true);
913
      memcpy (&chatterchannels[chatterchannel_count], &cc, sizeof (chatterchannel_t)); // now save data
914
      chatterchannel_count++; // we know now one sought game more
915
   }
916
 
917
   // free the big buffer space we used
918
   SAFE_free ((void **) &big_buffer);
919
 
920
   // now that the chatter channels are read, find again the one that was previously selected
921
 
922
   // if no chatter channel is selected yet, and we have a natural language channel exists and this channel is not open yet...
923
   if ((previouslyselected_channelid == -1) && (naturallanguagechannel_index != -1) && !chatterchannels[naturallanguagechannel_index].is_open)
924
      Player_SendBuffer_Add (player, 1000, L"+channel %d\n", chatterchannels[naturallanguagechannel_index].id); // open this channel
925
 
926
   // cycle through all the chatter channels we know...
927
   for (chatterchannel_index = 0; chatterchannel_index < chatterchannel_count; chatterchannel_index++)
928
      if ((previouslyselected_channelid != -1) && (chatterchannels[chatterchannel_index].id == previouslyselected_channelid))
929
         break; // break as soon as we find it
930
 
931
   // have we found none ?
932
   if (chatterchannel_index == chatterchannel_count)
933
   {
934
      // cycle through all the chatter channels we know...
935
      for (chatterchannel_index = 0; chatterchannel_index < chatterchannel_count; chatterchannel_index++)
936
         if (chatterchannels[chatterchannel_index].is_open && (wcsistr (chatterchannels[chatterchannel_index].theme, L"chat") != NULL))
937
            break; // break on the first open general chatter channel we find
938
 
939
      // have we found none ?
940
      if (chatterchannel_index == chatterchannel_count)
941
         chatterchannel_index = 0; // ultimate fallback, select the first channel
942
   }
943
 
944
   selected_chatterchannel = &chatterchannels[chatterchannel_index]; // in the end, select the channel that was previously selected
945
 
946
   chatterchannels_updated = true; // remember chatter channels list is to be updated
947
   return; // finished evaluating this channel list
948
}
949
 
950
 
951
void EvaluateServerReply_SoughtList (player_t *player)
952
{
953
   // this function parses a network reply and evaluates it, deciding what to do
954
 
955
   wchar_t line_buffer[256];
956
   soughtgame_t sg;
957
   wchar_t *field_start;
958
   wchar_t *string_pointer;
959
 
960
   // is the sought games footer bit NOT present ?
961
   if (!IS_FIELD_PRESENT (field_start, L" ads displayed.") && !IS_FIELD_PRESENT (field_start, L" ad displayed."))
962
      return; // if so, this reply can't be a sought games list so just return
963
 
964
   SAFE_free ((void **) &soughtgames); // free the sought games list we know
965
   soughtgame_count = 0; // reset the sought games count
966
 
967
   // now read line per line
968
   string_pointer = player->recvbuffer; // start at the first character
969
   while ((string_pointer = wcsgets (line_buffer, sizeof (line_buffer), string_pointer)) != NULL)
970
   {
971
      if (line_buffer[0] == L'\n')
972
         continue; // discard empty lines
973
      else if ((wcsstr (line_buffer, L" ads displayed.") != NULL) || (wcsstr (line_buffer, L" ad displayed.") != NULL))
974
         break; // if it's the end of the list, stop reading
975
 
976
      // now parse the sought games data
977
      field_start = line_buffer;
978
      memset (&sg, 0, sizeof (sg));
979
 
980
      while (*field_start && iswspace (*field_start))
981
         field_start++; // skip leading spaces
982
      if (*field_start == 0)
983
         continue; // discard bogus lines
984
 
985
      sg.id = _wtoi (field_start); // read sought game id
986
      REACH_NEXT_FIELD_ELSE (field_start, continue);
987
      if ((*field_start != L'-') && (*field_start != L'+'))
988
         sg.rating = _wtoi (field_start); // read player rating
989
      REACH_NEXT_FIELD_ELSE (field_start, continue);
990
      ReadNickname (sg.nickname, WCHAR_SIZEOF (sg.nickname), field_start); // read nickname
991
      REACH_NEXT_FIELD_ELSE (field_start, continue);
992
      sg.initial_time = (float) _wtof (field_start); // read initial time
993
      REACH_NEXT_FIELD_ELSE (field_start, continue);
994
      sg.increment = (float) _wtof (field_start); // read Fischer increment
995
      REACH_NEXT_FIELD_ELSE (field_start, continue);
996
      sg.rating_type = (*field_start == L'r' ? GAMERATINGTYPE_SUPPORTEDRATED : GAMERATINGTYPE_SUPPORTEDUNRATED); // read whether it is rated or not
997
      REACH_NEXT_FIELD_ELSE (field_start, continue);
998
      ReadGamename (sg.game_type, WCHAR_SIZEOF (sg.game_type), field_start); // read game type
999
      sg.game_type[0] = towupper (sg.game_type[0]); // capitalize first character
1000
      REACH_NEXT_FIELD_ELSE (field_start, continue);
1001
      sg.color = COLOR_UNSPECIFIED; // set unspecified color until told otherwise
1002
      if (*field_start == L'[')
1003
      {
1004
         if (field_start[1] == L'b') sg.color = COLOR_BLACK; // read specified color
1005
         else if (field_start[1] == L'w') sg.color = COLOR_WHITE;
1006
         REACH_NEXT_FIELD_ELSE (field_start, continue);
1007
      }
1008
      if (swscanf_s (field_start, L"%d-%d", &sg.lowest_accepted, &sg.highest_accepted) != 2)
1009
         continue; // read minimal and maximal accepted ELO, and discard bogus lines
1010
 
1011
      // read whether the game will start automatically and whether the player's filter formula will be checked
1012
      if (wcsstr (field_start, L" mf") != NULL)
1013
      {
1014
         sg.manual_start = true;
1015
         sg.formula_checked = true;
1016
      }
1017
      else if (wcsstr (field_start, L" m") != NULL)
1018
         sg.manual_start = true;
1019
      else if (wcsstr (field_start, L" f") != NULL)
1020
         sg.formula_checked = true;
1021
 
1022
      // is this variant unsupported ?
1023
      if ((wcscmp (sg.game_type, L"Untimed") != 0) && (wcscmp (sg.game_type, L"Standard") != 0)
1024
            && (wcscmp (sg.game_type, L"Blitz") != 0) && (wcscmp (sg.game_type, L"Lightning") != 0))
1025
      {
1026
         sg.rating = 0;
1027
         sg.initial_time = 0.0f;
1028
         sg.increment = 0.0f;
1029
         sg.rating_type = GAMERATINGTYPE_UNSUPPORTED; // if so, clear some values to clean up the display
1030
         sg.color = COLOR_UNSPECIFIED;
1031
         sg.lowest_accepted = 0;
1032
         sg.highest_accepted = 0;
1033
         sg.manual_start = true;
1034
         sg.formula_checked = false;
1035
      }
1036
 
1037
      // all parsing was OK, reallocate sought games list to have one sought game more
1038
      soughtgames = (soughtgame_t *) SAFE_realloc (soughtgames, soughtgame_count, soughtgame_count + 1, sizeof (soughtgame_t), true);
1039
      memcpy (&soughtgames[soughtgame_count], &sg, sizeof (soughtgame_t)); // now save data
1040
      soughtgame_count++; // we know now one sought game more
1041
   }
1042
 
1043
   soughtgames_updated = true; // remember sought games display is to be updated
1044
   lastsought_time = current_time; // remember when we were last updated
1045
   return; // finished evaluating this sought games list
1046
}
1047
 
1048
 
1049
void EvaluateServerReply_PlayersList (player_t *player)
1050
{
1051
   // this function parses a network reply and evaluates it, deciding what to do
1052
 
1053
   wchar_t line_buffer[256];
1054
   onlineplayer_t olp;
1055
   wchar_t *field_stop;
1056
   wchar_t *string_pointer;
1057
   int buffer_length;
1058
   int char_index;
1059
 
1060
   // is the players list footer bit NOT present ?
1061
   if (!IS_FIELD_PRESENT (field_stop, L"(*) indicates system administrator."))
1062
      return; // if so, this reply can't be a players list so just return
1063
 
1064
   SAFE_free ((void **) &onlineplayers); // free the online players list we know
1065
   onlineplayer_count = 0; // reset the players count
1066
 
1067
   // format the player list well. We slightly modify recvbuffer here.
1068
   // for each character in string...
1069
   buffer_length = wcslen (player->recvbuffer);
1070
   for (char_index = 0; char_index < buffer_length - 1; char_index++)
1071
   {
1072
      // is it a separator (two spaces) ?
1073
      if ((player->recvbuffer[char_index] == L' ') && (player->recvbuffer[char_index + 1] == L' '))
1074
      {
1075
         while (iswspace (player->recvbuffer[char_index]))
1076
         {
1077
            player->recvbuffer[char_index] = L'\n'; // replace all spaces by newlines
1078
            char_index++; // skip all spaces and reach the next non-space character
1079
         }
1080
      }
1081
   }
1082
 
1083
   // now read line per line
1084
   string_pointer = player->recvbuffer; // start at the first character
1085
   while ((string_pointer = wcsgets (line_buffer, sizeof (line_buffer), string_pointer)) != NULL)
1086
   {
1087
      if (line_buffer[0] == L'\n')
1088
         continue; // discard empty lines
1089
      else if (wcsstr (line_buffer, L"(*) indicates system administrator.") != NULL)
1090
         break; // if it's the end of the list, stop parsing
1091
 
1092
      // now parse the player data
1093
 
1094
      // parse the handle status
1095
      if (wcschr (line_buffer, L'^') != NULL) olp.handlestatus = HANDLESTATUS_INGAME; // player is in game
1096
      else if (wcschr (line_buffer, L'~') != NULL) olp.handlestatus = HANDLESTATUS_INSIMULATION; // player is in simulation
1097
      else if (wcschr (line_buffer, L'&') != NULL) olp.handlestatus = HANDLESTATUS_INTOURNAMENT; // player is in tournament
1098
      else if (wcschr (line_buffer, L'#') != NULL) olp.handlestatus = HANDLESTATUS_EXAMININGAGAME; // player is examining a game
1099
      else if (wcschr (line_buffer, L':') != NULL) olp.handlestatus = HANDLESTATUS_NOTOPENFORAMATCH; // player is not open for a match
1100
      else if (wcschr (line_buffer, L'.') != NULL) olp.handlestatus = HANDLESTATUS_INACTIVEORBUSY; // player is inactive or busy
1101
      else olp.handlestatus = HANDLESTATUS_AVAILABLE; // player is available
1102
 
1103
      // parse the handle codes
1104
      olp.handlecodes = 0;
1105
      if (wcsstr (line_buffer, L"(*)") != NULL) olp.handlecodes |= HANDLECODE_ADMINISTRATOR; // player is administrator
1106
      if (wcsstr (line_buffer, L"(B)") != NULL) olp.handlecodes |= HANDLECODE_BLINDFOLD; // player is blindfold
1107
      if (wcsstr (line_buffer, L"(C)") != NULL) olp.handlecodes |= HANDLECODE_COMPUTER; // player is a computer
1108
      if (wcsstr (line_buffer, L"(T)") != NULL) olp.handlecodes |= HANDLECODE_TEAM; // player is several persons
1109
      if (wcsstr (line_buffer, L"(U)") != NULL) olp.handlecodes |= HANDLECODE_UNREGISTERED; // player is unregistered
1110
      if (wcsstr (line_buffer, L"(CA)") != NULL) olp.handlecodes |= HANDLECODE_CHESSADVISOR; // player is a chess advisor
1111
      if (wcsstr (line_buffer, L"(SR)") != NULL) olp.handlecodes |= HANDLECODE_SERVICEREPRESENTATIVE; // player is a service representative
1112
      if (wcsstr (line_buffer, L"(TD)") != NULL) olp.handlecodes |= HANDLECODE_TOURNAMENTDIRECTOR; // player is a tournament director
1113
      if (wcsstr (line_buffer, L"(TM)") != NULL) olp.handlecodes |= HANDLECODE_MAMERMANAGER; // player is a mamer manager
1114
      if (wcsstr (line_buffer, L"(FM)") != NULL) olp.handlecodes |= HANDLECODE_FIDEMASTER; // player is a FIDE master
1115
      if (wcsstr (line_buffer, L"(IM)") != NULL) olp.handlecodes |= HANDLECODE_FIDEINTERNATIONALMASTER; // player is a FIDE international master
1116
      if (wcsstr (line_buffer, L"(GM)") != NULL) olp.handlecodes |= HANDLECODE_FIDEGREATMASTER; // player is a FIDE grand master
1117
      if (wcsstr (line_buffer, L"(WIM)") != NULL) olp.handlecodes |= HANDLECODE_FIDEWOMENSINTERNATIONALMASTER; // player is a FIDE woman international master
1118
      if (wcsstr (line_buffer, L"(WGM)") != NULL) olp.handlecodes |= HANDLECODE_FIDEWOMENSGREATMASTER; // player is a FIDE woman great master
1119
 
1120
      // get to the first non-numeric character
1121
      buffer_length = wcslen (line_buffer);
1122
      for (char_index = 0; char_index < buffer_length; char_index++)
1123
         if (!iswdigit (line_buffer[char_index]) && (line_buffer[char_index] != L'+') && (line_buffer[char_index] != L'-'))
1124
            break; // break as soon as we find it
1125
 
1126
      if (char_index >= buffer_length - 1)
1127
         continue; // consistency check: this player is bogus
1128
 
1129
      // is it a E ? else is it a P ?
1130
      if (line_buffer[char_index] == L'E') olp.ratingtype = OPPONENTRATINGTYPE_ESTIMATED; // this player's rating is estimated
1131
      else if (line_buffer[char_index] == L'P') olp.ratingtype = OPPONENTRATINGTYPE_PROVISIONAL; // this player's rating is provisional
1132
      else olp.ratingtype = OPPONENTRATINGTYPE_DEFAULT; // this player's rating is normal
1133
 
1134
      wcscpy_s (olp.nickname, WCHAR_SIZEOF (olp.nickname), &line_buffer[char_index + 1]); // copy nickname
1135
      if ((field_stop = wcschr (olp.nickname, L'(')) != NULL)
1136
         *field_stop = 0; // separate nickname from its handle flags
1137
 
1138
      // read opponent rating
1139
      olp.rating = _wtoi (line_buffer); // ++++ (unregistered) and ---- (no rating) will be translated as 0
1140
 
1141
      // all parsing was OK, reallocate online players list to have one player more
1142
      onlineplayers = (onlineplayer_t *) SAFE_realloc (onlineplayers, onlineplayer_count, onlineplayer_count + 1, sizeof (onlineplayer_t), true);
1143
      memcpy (&onlineplayers[onlineplayer_count], &olp, sizeof (onlineplayer_t)); // now save data
1144
      onlineplayer_count++; // we know now one player more
1145
   }
1146
 
1147
   onlineplayers_updated = true; // remember online player list is to be updated
1148
   lastonlineplayers_time = current_time; // remember when we were last updated
1149
   return; // finished evaluating this players list
1150
}
1151
 
1152
 
1153
void EvaluateServerReply_GameStarting (player_t *player)
1154
{
1155
   // this function parses a network reply and evaluates it, deciding what to do
1156
 
1157
   wchar_t white_name[32];
1158
   wchar_t black_name[32];
1159
   wchar_t *field_start;
1160
   player_t *local_player;
1161
 
1162
   // is the game starting notification header bit NOT present ?
1163
   if (!IS_FIELD_PRESENT_AT_BEGINNING_OF_LINE (field_start, L"Creating: "))
1164
      return; // if so, this reply can't be a game starting notification so just return
1165
 
1166
   // read the interesting parameters, namely white player's name (so that we know which side to display)
1167
   if (swscanf_s (field_start, L"Creating: %s %*s %s %*s %*s %*s %*d %*d", white_name, WCHAR_SIZEOF (white_name), black_name, WCHAR_SIZEOF (black_name)) != 2)
1168
      Debug_Log (L"===WARNING: unable to parse game starting notification message!===\n%s\n======\n", field_start);
1169
 
1170
   local_player = Player_FindByType (PLAYER_HUMAN); // get a pointer to the local player
1171
 
1172
   // is local player NOT the white color AND should be, OR is local player white color AND should NOT be ?
1173
   if (((local_player->color != COLOR_WHITE) && (wcscmp (white_name, local_player->name) == 0))
1174
       || ((local_player->color == COLOR_WHITE) && (wcscmp (white_name, local_player->name) != 0)))
1175
   {
1176
      Debug_Log (L"===Game starting and local player is not white and should be (or is white and should not be), swapping sides===\n");
1177
      the_board.want_playerswap = true; // swap sides
1178
   }
1179
 
1180
   // display the game starting message notification
1181
   Scene_SetText (&the_scene.gui.central_text, 50.0f, 50.0f, -1, ALIGN_CENTER, ALIGN_CENTER, ALIGN_CENTER, centermsg_fontindex, RGBA_TO_RGBACOLOR (255, 255, 255, 191),
1182
                  5.0f, true, L"%s\n%s (%s) %s %s (%s)", LOCALIZE (L"NewGame_Title"), white_name, LOCALIZE (L"Games_White"), LOCALIZE (L"Versus"), black_name, LOCALIZE (L"Games_Black"));
1183
 
1184
   // close any possible singleton window
1185
   if (IsWindow (hChatterChannelsWnd))
1186
      DestroyWindow (hChatterChannelsWnd);
1187
   if (IsWindow (hGamesWnd))
1188
      DestroyWindow (hGamesWnd); // PGN games window (improbable)
1189
   if (IsWindow (hMOTDWnd))
1190
      DestroyWindow (hMOTDWnd);
1191
   if (IsWindow (hOpponentsWnd))
1192
      DestroyWindow (hOpponentsWnd);
1193
   if (IsWindow (hSoughtWnd))
1194
      DestroyWindow (hSoughtWnd);
1195
 
1196
   return; // finished evaluating the game starting notification
1197
}
1198
 
1199
 
1200
void EvaluateServerReply_GameState (player_t *player)
1201
{
1202
   // this function parses a network reply and evaluates it, deciding what to do
1203
 
1204
   // Format of style12 computer-parseable lines (ICC/FICS):
1205
   // 
1206
   // <12> rnbqkb-r pppppppp -----n-- -------- ----P--- -------- PPPPKPPP RNBQ-BNR B -1 0 0 1 1 0 7 Newton Einstein 1 2 12 39 39 119 122 2 K/e1-e2 (0:06) Ke2 0
1207
   // 
1208
   // This string always begins on a new line, and there are always exactly 31 non-empty fields separated by blanks. The fields are:
1209
   // 
1210
   // * the string "<12>" to identify this line.
1211
   // * eight fields representing the board position. First one is White's 8th rank (also Black's 1st rank), then White's 7th rank (also Black's 2nd), etc.
1212
   // * color whose turn it is to move ("B" or "W")
1213
   // * -1 if the previous move was NOT a double pawn push, otherwise the chess board file  (numbered 0--7 for a--h) in which the double push was made
1214
   // * can White still castle short? (0=no, 1=yes)
1215
   // * can White still castle long?
1216
   // * can Black still castle short?
1217
   // * can Black still castle long?
1218
   // * the number of moves made since the last irreversible move (0 if last move was irreversible. If value is >= 100, game can be declared a draw due to the 50 move rule.)
1219
   // * The game number
1220
   // * White's name
1221
   // * Black's name
1222
   // * my relation to this game:
1223
   //     -3 isolated position, such as for "ref 3" or the "sposition" command
1224
   //     -2 I am observing game being examined
1225
   //      2 I am the examiner of this game
1226
   //     -1 I am playing, it is my opponent's move
1227
   //      1 I am playing and it is my move
1228
   //      0 I am observing a game being played
1229
   // * initial time (in seconds) of the match
1230
   // * increment In seconds) of the match
1231
   // * White material strength
1232
   // * Black material strength
1233
   // * White's remaining time
1234
   // * Black's remaining time
1235
   // * the number of the move about to be made (standard chess numbering -- White's and Black's first moves are both 1, etc.)
1236
   // * verbose coordinate notation for the previous move ("none" if there were none) [note this used to be broken for examined games]
1237
   // * time taken to make previous move "(min:sec)".
1238
   // * pretty notation for the previous move ("none" if there is none)
1239
   // * flip field for board orientation: 1 = Black at bottom, 0 = White at bottom.
1240
   // 
1241
   // In the future, new fields may be added to the end of the data string, so programs should parse from left to right.
1242
   // 
1243
   // Special information for bughouse games
1244
   // --------------------------------------
1245
   // When showing positions from bughouse games, a second line showing piece holding is given, with "<b1>" at the beginning, for example:
1246
   //   <b1> game 6 white [PNBBB] black [PNB]
1247
   // Also, when pieces are "passed" during bughouse, a short data string -- not the entire board position -- is sent.  For example:
1248
   //   <b1> game 52 white [NB] black [N] <- BN
1249
   // The final two letters indicate the piece that was passed; in the above example, a knight (N) was passed to Black.
1250
   // A prompt may preceed the <b1> header.
1251
 
1252
   wchar_t positions[65];
1253
   wchar_t move_color_as_string[2];
1254
   int move_color;
1255
   int player_color;
1256
   int pawnrush_column;
1257
   int can_white_castle_short;
1258
   int can_white_castle_long;
1259
   int can_black_castle_short;
1260
   int can_black_castle_long;
1261
   int number_of_moves_since_last_irreversible_move;
1262
   int game_number;
1263
   wchar_t white_name[32];
1264
   wchar_t black_name[32];
1265
   int my_status;
1266
   int white_remaining_time_in_seconds;
1267
   int black_remaining_time_in_seconds;
1268
   int turn_number_1_based;
1269
   int move_index;
1270
   wchar_t pretty_movestring[8];
1271
   boardmove_t move;
1272
   wchar_t *field_start;
1273
   int recognized_fields;
1274
   boardmove_t *last_move;
1275
 
1276
   // is it NOT a style12 line reply ?
1277
   if (!IS_FIELD_PRESENT_AT_BEGINNING_OF_LINE (field_start, L"<12> "))
1278
      return; // if so, this reply can't be a style12 notification so just return
1279
 
1280
   recognized_fields = swscanf_s (field_start, L"<12> " // style12 header
1281
                                               L"%s %s %s %s %s %s %s %s " // "rnbqkbnr pppppppp -------- -------- -------- -------- PPPPPPPP RNBQKBNR"
1282
                                               L"%s %d %d %d %d %d %d %d " // "W -1 1 1 1 1 0 2"
1283
                                               L"%s %s %d %*d %*d %*d %*d " // "guestpmtelnet GuestJXTJ -1 2 12 39 39"
1284
                                               L"%d %d %d %*s %*s %s %*d", // "120 120 1 none (0:00) none 1 0 0"
1285
                                               &positions[0 * 8], 9, &positions[1 * 8], 9, &positions[2 * 8], 9, &positions[3 * 8], 9, &positions[4 * 8], 9, &positions[5 * 8], 9, &positions[6 * 8], 9, &positions[7 * 8], 9,
1286
                                               move_color_as_string, WCHAR_SIZEOF (move_color_as_string), &pawnrush_column, &can_white_castle_short, &can_white_castle_long, &can_black_castle_short, &can_black_castle_long, &number_of_moves_since_last_irreversible_move, &game_number,
1287
                                               white_name, WCHAR_SIZEOF (white_name), black_name, WCHAR_SIZEOF (black_name), &my_status,
1288
                                               &white_remaining_time_in_seconds, &black_remaining_time_in_seconds, &turn_number_1_based, pretty_movestring, WCHAR_SIZEOF (pretty_movestring));
1289
   if (recognized_fields != 23)
1290
      return; // unparseable style12 reply
1291
 
1292
   // remember we are in game and which game it is
1293
   player->is_in_game = true;
1294
   player->game_number = game_number;
1295
 
1296
   // convert some data into easier formats first. The color which just moved is the opposite of the color to move now
1297
   move_color = (towupper (move_color_as_string[0]) == L'W' ? COLOR_BLACK : COLOR_WHITE);
1298
   move_index = (2 * turn_number_1_based) - 2 + (move_color == COLOR_WHITE ? 1 : 0);
1299
 
1300
   // save the unquestionable parameters (direct it to the opposite player if the board is going to be swapped)
1301
   player_color = the_board.want_playerswap ? COLOR_WHITE : COLOR_BLACK;
1302
   ReadNickname (the_board.players[player_color].name, WCHAR_SIZEOF (the_board.players[player_color].name), black_name);
1303
   the_board.players[player_color].remaining_seconds = black_remaining_time_in_seconds;
1304
 
1305
   player_color = the_board.want_playerswap ? COLOR_BLACK : COLOR_WHITE;
1306
   ReadNickname (the_board.players[player_color].name, WCHAR_SIZEOF (the_board.players[player_color].name), white_name);
1307
   the_board.players[player_color].remaining_seconds = white_remaining_time_in_seconds;
1308
 
1309
   // is it an initial board position ?
1310
   if (wcscmp (pretty_movestring, L"none") == 0)
1311
   {
1312
      Debug_Log (L"===Setting up board according to chess server's specifications and beginning new game===\n");
1313
 
1314
      // set up the board according to what the chess server tells us
1315
      memset (&move, 0, sizeof (move));
1316
      Move_SetupFromStyle12 (&move, positions, move_color, pawnrush_column,
1317
                              (can_white_castle_short != 0), (can_white_castle_long != 0), (can_black_castle_short != 0), (can_black_castle_long != 0), pretty_movestring);
1318
      Board_Reset (&the_board, move.fen_string);
1319
   }
1320
 
1321
   // else play the move and swap sides
1322
   else
1323
   {
1324
      Debug_Log (L"===Received board status update from chess server===\n");
1325
 
1326
      // are we appending a new move ?
1327
      if (((move_color == player->color) && (move_index == the_board.move_count)) // either a new move by our opponent
1328
          || ((move_color != player->color) && (move_index == the_board.move_count - 1))) // or a confirmation of a move already played by the local player
1329
      {
1330
         Debug_Log (L"===Appending new move %d===\n", move_index);
1331
 
1332
         // get a pointer to the previous move
1333
         last_move = &the_board.moves[the_board.move_count - 1];
1334
 
1335
         // is the server reporting the remote player's move ?
1336
         if (move_color == player->color)
1337
         {
1338
            // evaluate the move string
1339
            wcscpy_s (move.pgntext, WCHAR_SIZEOF (move.pgntext), pretty_movestring);
1340
            if (!Move_SetupFromSAN (last_move, &move, player->color))
1341
               Debug_Log (L"===WARNING: unable to interpret server's table state while evaluating its notification of remote player move!===\n%s\n======\n", pretty_movestring);
1342
 
1343
            // play the remote opponent's move
1344
            Board_AppendMove (&the_board, move.source[0], move.source[1], move.target[0], move.target[1], move.promotion_type, NULL);
1345
 
1346
            the_board.has_playerchanged = true; // remember players changed
1347
            animation_endtime = current_time + ANIMATION_DURATION; // play move animation now
1348
            sound_playtime = current_time + ANIMATION_DURATION - 0.1f; // play sound near the end of animation
1349
         }
1350
 
1351
         // else the server is acknowledging the local player's move
1352
         else
1353
         {
1354
            // evaluate the move string
1355
            wcscpy_s (last_move->pgntext, WCHAR_SIZEOF (last_move->pgntext), pretty_movestring);
1356
            if (!Move_SetupFromSAN (&the_board.moves[the_board.move_count - 2], last_move, last_move->color))
1357
               Debug_Log (L"===WARNING: unable to interpret server's table state while evaluating its reply after local player move!===\n%s\n======\n", pretty_movestring);
1358
         }
1359
 
1360
         // in case a new move was appended, update the last move pointer
1361
         last_move = &the_board.moves[the_board.move_count - 1];
1362
      }
1363
 
1364
      // else the server must be time-warping the game backwards
1365
      else
1366
      {
1367
         Debug_Log (L"===Backing up to move %d===\n", move_index);
1368
 
1369
         last_move = &the_board.moves[move_index]; // get a pointer to the move we're backing up to
1370
         the_board.move_count = move_index + 1; // update the board's move count
1371
         if (the_board.viewed_move > the_board.move_count - 1)
1372
            the_board.viewed_move = the_board.move_count - 1; // and the board's viewed move as well
1373
 
1374
         // send a notification to the player's chat window
1375
         Interlocutor_Notify (Interlocutor_FindOrCreate (player->name), LOCALIZE (L"Chat_TakebackAccepted"));
1376
      }
1377
 
1378
      // make the server set it up correctly
1379
      Move_SetupFromStyle12 (last_move, positions, move_color, pawnrush_column,
1380
                              (can_white_castle_short != 0), (can_white_castle_long != 0), (can_black_castle_short != 0), (can_black_castle_long != 0), pretty_movestring);
1381
   }
1382
 
1383
   the_board.game_state = STATE_PLAYING; // remember that a game is currently playing
1384
   the_board.reevaluate = true; // and reeevaluate the board
1385
   return; // finished evaluating this style12 notification line
1386
}
1387
 
1388
 
1389
void EvaluateServerReply_GameResults (player_t *player)
1390
{
1391
   // this function parses a network reply and evaluates it, deciding what to do
1392
 
1393
   wchar_t *field_start;
1394
   int game_number;
1395
 
1396
   // is the game results notification header bit NOT present ?
1397
   if (!IS_FIELD_PRESENT_AT_BEGINNING_OF_LINE (field_start, L"{Game "))
1398
      return; // if so, this reply can't be a game results notification so just return
1399
 
1400
   // are we NOT in game yet OR is it a game creation message ?
1401
   if (!player->is_in_game || (wcsstr (field_start, L") Creating") != NULL))
1402
      return; // if so, this message is not a game results but a game creation message
1403
 
1404
   // verify it's for the game we're playing
1405
   if (swscanf_s (field_start, L"{Game %d ", &game_number) != 1)
1406
   {
1407
      Debug_Log (L"===WARNING: unable to parse game results notification message!===\n%s\n======\n", field_start);
1408
      return; // on error, drop a warning in the log file and return
1409
   }
1410
   if (game_number != player->game_number)
1411
   {
1412
      Debug_Log (L"===WARNING: received game results notification message with wrong game number! Ignoring.===\n");
1413
      return; // on error, drop a warning in the log file and return
1414
   }
1415
 
1416
   ////////////////////////////
1417
   // interpret the game result
1418
 
1419
   // do the white win ?
1420
   if (wcsstr (field_start, L"} 1-0") != NULL)
1421
   {
1422
      // is it a checkmate ?
1423
      if (wcsstr (field_start, L"checkmate") != NULL)
1424
      {
1425
         Debug_Log (L"===Server tells us that black is checkmate: white wins!===\n");
1426
         the_board.game_state = STATE_WHITEWIN_CHECKMATE; // remember game state
1427
      }
1428
 
1429
      // else it must be a resign, a forfeit or an adjudication
1430
      else
1431
      {
1432
         Debug_Log (L"===Server tells us that black [resigns|forfeits|loses adjudication]: white wins!===\n");
1433
         the_board.game_state = STATE_WHITEWIN_RESIGNORFORFEIT; // remember game state
1434
      }
1435
 
1436
      // if white player is human, play the victory sound, else, play defeat sound
1437
      Audio_PlaySound (the_board.players[COLOR_WHITE].type == PLAYER_HUMAN ? SOUNDTYPE_VICTORY : SOUNDTYPE_DEFEAT);
1438
   }
1439
 
1440
   // else do the black win ?
1441
   else if (wcsstr (field_start, L"} 0-1") != NULL)
1442
   {
1443
      // is it a checkmate ?
1444
      if (wcsstr (field_start, L" checkmate") != NULL)
1445
      {
1446
         Debug_Log (L"===Server tells us that white is checkmate: black wins!===\n");
1447
         the_board.game_state = STATE_BLACKWIN_CHECKMATE; // remember game state
1448
      }
1449
 
1450
      // else it must be a resign, a forfeit or an adjudication
1451
      else
1452
      {
1453
         Debug_Log (L"===Server tells us that white [resigns|forfeits|loses adjudication]: black wins!===\n");
1454
         the_board.game_state = STATE_BLACKWIN_RESIGNORFORFEIT; // remember game state
1455
      }
1456
 
1457
      // if black player is human, play the victory sound, else, play defeat sound
1458
      Audio_PlaySound (the_board.players[COLOR_BLACK].type == PLAYER_HUMAN ? SOUNDTYPE_VICTORY : SOUNDTYPE_DEFEAT);
1459
   }
1460
 
1461
   // else is it a draw ?
1462
   else if (wcsstr (field_start, L"} 1/2-1/2") != NULL)
1463
   {
1464
      // is it a stalemate ?
1465
      if (wcsstr (field_start, L" stalemate") != NULL)
1466
      {
1467
         Debug_Log (L"===Server tells us it's a stalemate: game is a draw===\n");
1468
         the_board.game_state = STATE_DRAW_STALEMATE; // remember game state
1469
      }
1470
 
1471
      // else is it a mutual agreement ?
1472
      else if (wcsstr (field_start, L" mutual agreement") != NULL)
1473
      {
1474
         Debug_Log (L"===Server tells us it's a draw by mutual agreement: game is a draw===\n");
1475
         the_board.game_state = STATE_DRAW_AGREEMENT; // remember game state
1476
      }
1477
 
1478
      // else it's another reason
1479
      else
1480
      {
1481
         Debug_Log (L"===Server tells us it's a draw for another reason: game is a draw===\n");
1482
         the_board.game_state = STATE_DRAW_OTHER; // remember game state
1483
      }
1484
 
1485
      // play a defeat sound
1486
      Audio_PlaySound (SOUNDTYPE_DEFEAT);
1487
   }
1488
 
1489
   // else is it an adjournment ?
1490
   else if (wcsstr (field_start, L"} *") != NULL)
1491
   {
1492
      Debug_Log (L"===Server tells the game is adjourned: game adjourned===\n");
1493
      the_board.game_state = STATE_ADJOURNED; // remember game state
1494
   }
1495
 
1496
   // else we can't interpret the game state
1497
   else
1498
   {
1499
      Debug_Log (L"===WARNING: unable to interpret game results notification message!===\n%s\n======\n", field_start);
1500
      return; // on error, drop a warning in the log file and return
1501
   }
1502
 
1503
   // remember player is no longer in game
1504
   player->is_in_game = false;
1505
   player->game_number = 0;
1506
 
1507
   // reevaluate the board and display the endgame dialog box
1508
   the_board.reevaluate = true;
1509
   DialogBox_EndGame ();
1510
 
1511
   return; // finished evaluating the game results notification
1512
}
1513
 
1514
 
1515
static void ReadNickname (wchar_t *nickname, size_t nickname_size, wchar_t *from_string)
1516
{
1517
   // helper function to read a nickname and strip it from its eventual flags
1518
 
1519
   unsigned int char_index;
1520
 
1521
   // as long as we don't read a forbidden character...
1522
   for (char_index = 0; char_index < nickname_size; char_index++)
1523
      if (iswalpha (from_string[char_index]))
1524
         nickname[char_index] = from_string[char_index]; // copy nickname one character after the other
1525
      else
1526
         break; // else stop copying immediately
1527
 
1528
   if (char_index < nickname_size)
1529
      nickname[char_index] = 0; // finish the string ourselves
1530
   else
1531
      nickname[nickname_size - 1] = 0; // truncate it if neeeded
1532
 
1533
   return; // finished
1534
}
1535
 
1536
 
1537
static void ReadGamename (wchar_t *gamename, size_t gamename_size, wchar_t *from_string)
1538
{
1539
   // helper function to read a game name
1540
 
1541
   unsigned int char_index;
1542
 
1543
   // as long as we don't read a forbidden character...
1544
   for (char_index = 0; char_index < gamename_size; char_index++)
1545
      if (iswgraph (from_string[char_index]))
1546
         gamename[char_index] = from_string[char_index]; // copy game name one character after the other
1547
      else
1548
         break; // else stop copying immediately
1549
 
1550
   if (char_index < gamename_size)
1551
      gamename[char_index] = 0; // finish the string ourselves
1552
   else
1553
      gamename[gamename_size - 1] = 0; // truncate it if neeeded
1554
 
1555
   return; // finished
1556
}
1557
 
1558
 
1559
static void ReadSpannedLine (wchar_t *outstring, size_t outstring_size, wchar_t *multiline_string)
1560
{
1561
   // this function linearizes a multiline string and takes out any special formatting character of it
1562
 
1563
   int length;
1564
   int read_index;
1565
   unsigned int write_index;
1566
 
1567
   length = wcslen (multiline_string); // get text length first
1568
 
1569
   // for each character in string...
1570
   write_index = 0;
1571
   for (read_index = 0; read_index < length; read_index++)
1572
   {
1573
      if (wcsncmp (&multiline_string[read_index], L"\\   ", 4) == 0)
1574
         read_index += 4; // if it's a new line indentation, skip it
1575
 
1576
      // are we NOT reading a newline followed by a backslash AND is it still room in the output string ?
1577
      if (!((read_index < length - 1) && (multiline_string[read_index] == L'\n') && (multiline_string[read_index + 1] == L'\\'))
1578
          && (write_index < outstring_size - 1))
1579
      {
1580
         if (multiline_string[read_index] == L'\n')
1581
            break; // if it's a newline (without backslash following), stop reading
1582
 
1583
         outstring[write_index] = multiline_string[read_index]; // else copy this character to output string
1584
         write_index++; // and advance in string
1585
      }
1586
   }
1587
 
1588
   outstring[write_index] = 0; // finish string
1589
   return; // and return
1590
}