App_Main.py 445 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940
  1. # ###########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. # Modified by Marius Stanciu (2019) #
  8. # ###########################################################
  9. import urllib.request
  10. import urllib.parse
  11. import urllib.error
  12. import getopt
  13. import random
  14. import simplejson as json
  15. import shutil
  16. import lzma
  17. from datetime import datetime
  18. import time
  19. import ctypes
  20. import traceback
  21. from shapely.geometry import Point, MultiPolygon
  22. from io import StringIO
  23. from reportlab.graphics import renderPDF
  24. from reportlab.pdfgen import canvas
  25. from reportlab.lib.units import inch, mm
  26. from reportlab.lib.pagesizes import landscape, portrait
  27. from svglib.svglib import svg2rlg
  28. import gc
  29. from xml.dom.minidom import parseString as parse_xml_string
  30. from multiprocessing.connection import Listener, Client
  31. from multiprocessing import Pool
  32. import socket
  33. # ####################################################################################################################
  34. # ################################### Imports part of FlatCAM #############################################
  35. # ####################################################################################################################
  36. # Various
  37. from Common import LoudDict
  38. from Common import color_variant
  39. from Common import ExclusionAreas
  40. from Bookmark import BookmarkManager
  41. from AppDatabase import ToolsDB2
  42. from vispy.gloo.util import _screenshot
  43. from vispy.io import write_png
  44. # FlatCAM defaults (preferences)
  45. from defaults import FlatCAMDefaults
  46. # FlatCAM Objects
  47. from AppGUI.preferences.OptionsGroupUI import OptionsGroupUI
  48. from AppGUI.preferences.PreferencesUIManager import PreferencesUIManager
  49. from AppObjects.ObjectCollection import *
  50. from AppObjects.FlatCAMObj import FlatCAMObj
  51. from AppObjects.AppObject import AppObject
  52. # FlatCAM Parsing files
  53. from AppParsers.ParseExcellon import Excellon
  54. from AppParsers.ParseGerber import Gerber
  55. from camlib import to_dict, dict2obj, ET, ParseError, Geometry, CNCjob
  56. # FlatCAM AppGUI
  57. from AppGUI.PlotCanvas import *
  58. from AppGUI.PlotCanvasLegacy import *
  59. from AppGUI.MainGUI import *
  60. from AppGUI.GUIElements import FCFileSaveDialog, message_dialog, FlatCAMSystemTray
  61. # FlatCAM Pre-processors
  62. from AppPreProcessor import load_preprocessors
  63. # FlatCAM AppEditors
  64. from AppEditors.FlatCAMGeoEditor import FlatCAMGeoEditor
  65. from AppEditors.FlatCAMExcEditor import FlatCAMExcEditor
  66. from AppEditors.FlatCAMGrbEditor import FlatCAMGrbEditor
  67. from AppEditors.FlatCAMTextEditor import TextEditor
  68. from AppParsers.ParseHPGL2 import HPGL2
  69. # FlatCAM Workers
  70. from AppProcess import *
  71. from AppWorkerStack import WorkerStack
  72. # FlatCAM Tools
  73. from AppTools import *
  74. # FlatCAM Translation
  75. import gettext
  76. import AppTranslation as fcTranslate
  77. import builtins
  78. if sys.platform == 'win32':
  79. import winreg
  80. from win32comext.shell import shell, shellcon
  81. fcTranslate.apply_language('strings')
  82. if '_' not in builtins.__dict__:
  83. _ = gettext.gettext
  84. class App(QtCore.QObject):
  85. """
  86. The main application class. The constructor starts the GUI and all other classes used by the program.
  87. """
  88. # ###############################################################################################################
  89. # ########################################## App ################################################################
  90. # ###############################################################################################################
  91. # ###############################################################################################################
  92. # ######################################### LOGGING #############################################################
  93. # ###############################################################################################################
  94. log = logging.getLogger('base')
  95. log.setLevel(logging.DEBUG)
  96. # log.setLevel(logging.WARNING)
  97. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  98. handler = logging.StreamHandler()
  99. handler.setFormatter(formatter)
  100. log.addHandler(handler)
  101. # ###############################################################################################################
  102. # #################################### Get Cmd Line Options #####################################################
  103. # ###############################################################################################################
  104. cmd_line_shellfile = ''
  105. cmd_line_shellvar = ''
  106. cmd_line_headless = None
  107. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>\n" \
  108. "FlatCam.py --shellvar=<1,'C:\\path',23>\n" \
  109. "FlatCam.py --headless=1"
  110. try:
  111. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  112. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=",
  113. "shellvar=",
  114. "headless=",
  115. "multiprocessing-fork="])
  116. except getopt.GetoptError:
  117. print(cmd_line_help)
  118. sys.exit(2)
  119. for opt, arg in cmd_line_options:
  120. if opt == '-h':
  121. print(cmd_line_help)
  122. sys.exit()
  123. elif opt == '--shellfile':
  124. cmd_line_shellfile = arg
  125. elif opt == '--shellvar':
  126. cmd_line_shellvar = arg
  127. elif opt == '--headless':
  128. try:
  129. cmd_line_headless = eval(arg)
  130. except NameError:
  131. pass
  132. # ###############################################################################################################
  133. # ################################### Version and VERSION DATE ##################################################
  134. # ###############################################################################################################
  135. version = 8.993
  136. version_date = "2020/08/01"
  137. beta = True
  138. engine = '3D'
  139. # current date now
  140. date = str(datetime.today()).rpartition('.')[0]
  141. date = ''.join(c for c in date if c not in ':-')
  142. date = date.replace(' ', '_')
  143. # ###############################################################################################################
  144. # ############################################ URLS's ###########################################################
  145. # ###############################################################################################################
  146. # URL for update checks and statistics
  147. version_url = "http://flatcam.org/version"
  148. # App URL
  149. app_url = "http://flatcam.org"
  150. # Manual URL
  151. manual_url = "http://flatcam.org/manual/index.html"
  152. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  153. gerber_spec_url = "https://www.ucamco.com/files/downloads/file/81/The_Gerber_File_Format_specification." \
  154. "pdf?7ac957791daba2cdf4c2c913f67a43da"
  155. excellon_spec_url = "https://www.ucamco.com/files/downloads/file/305/the_xnc_file_format_specification.pdf"
  156. bug_report_url = "https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open"
  157. # this variable will hold the project status
  158. # if True it will mean that the project was modified and not saved
  159. should_we_save = False
  160. # flag is True if saving action has been triggered
  161. save_in_progress = False
  162. # ###############################################################################################################
  163. # ####################################### APP Signals ######################################################
  164. # ###############################################################################################################
  165. # Inform the user
  166. # Handled by:
  167. # * App.info() --> Print on the status bar
  168. inform = QtCore.pyqtSignal([str], [str, bool])
  169. app_quit = QtCore.pyqtSignal()
  170. # General purpose background task
  171. worker_task = QtCore.pyqtSignal(dict)
  172. # File opened
  173. # Handled by:
  174. # * register_folder()
  175. # * register_recent()
  176. # Note: Setting the parameters to unicode does not seem
  177. # to have an effect. Then are received as Qstring
  178. # anyway.
  179. # File type and filename
  180. file_opened = QtCore.pyqtSignal(str, str)
  181. # File type and filename
  182. file_saved = QtCore.pyqtSignal(str, str)
  183. # Percentage of progress
  184. progress = QtCore.pyqtSignal(int)
  185. # Emitted when a new object has been added or deleted from/to the collection
  186. object_status_changed = QtCore.pyqtSignal(object, str, str)
  187. message = QtCore.pyqtSignal(str, str, str)
  188. # Emmited when shell command is finished(one command only)
  189. shell_command_finished = QtCore.pyqtSignal(object)
  190. # Emitted when multiprocess pool has been recreated
  191. pool_recreated = QtCore.pyqtSignal(object)
  192. # Emitted when an unhandled exception happens
  193. # in the worker task.
  194. thread_exception = QtCore.pyqtSignal(object)
  195. # used to signal that there are arguments for the app
  196. args_at_startup = QtCore.pyqtSignal(list)
  197. # a reusable signal to replot a list of objects
  198. # should be disconnected after use so it can be reused
  199. replot_signal = pyqtSignal(list)
  200. # signal emitted when jumping
  201. jump_signal = pyqtSignal(tuple)
  202. # signal emitted when jumping
  203. locate_signal = pyqtSignal(tuple, str)
  204. # close app signal
  205. close_app_signal = pyqtSignal()
  206. # will perform the cleanup operation after a Graceful Exit
  207. # usefull for the NCC Tool and Paint Tool where some progressive plotting might leave
  208. # graphic residues behind
  209. cleanup = pyqtSignal()
  210. def __init__(self, user_defaults=True):
  211. """
  212. Starts the application.
  213. :return: app
  214. :rtype: App
  215. """
  216. super().__init__()
  217. App.log.info("FlatCAM Starting...")
  218. self.main_thread = QtWidgets.QApplication.instance().thread()
  219. # ############################################################################################################
  220. # ################# Setup the listening thread for another instance launching with args ######################
  221. # ############################################################################################################
  222. if sys.platform == 'win32' or sys.platform == 'linux':
  223. # make sure the thread is stored by using a self. otherwise it's garbage collected
  224. self.th = QtCore.QThread()
  225. self.th.start(priority=QtCore.QThread.LowestPriority)
  226. self.new_launch = ArgsThread()
  227. self.new_launch.open_signal[list].connect(self.on_startup_args)
  228. self.new_launch.moveToThread(self.th)
  229. self.new_launch.start.emit()
  230. # ############################################################################################################
  231. # ########################################## OS-specific #####################################################
  232. # ############################################################################################################
  233. portable = False
  234. # Folder for user settings.
  235. if sys.platform == 'win32':
  236. if platform.architecture()[0] == '32bit':
  237. App.log.debug("Win32!")
  238. else:
  239. App.log.debug("Win64!")
  240. # #######################################################################################################
  241. # ####### CONFIG FILE WITH PARAMETERS REGARDING PORTABILITY #############################################
  242. # #######################################################################################################
  243. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  244. try:
  245. with open(config_file, 'r'):
  246. pass
  247. except FileNotFoundError:
  248. config_file = os.path.dirname(os.path.realpath(__file__)) + '\\config\\configuration.txt'
  249. try:
  250. with open(config_file, 'r') as f:
  251. try:
  252. for line in f:
  253. param = str(line).replace('\n', '').rpartition('=')
  254. if param[0] == 'portable':
  255. try:
  256. portable = eval(param[2])
  257. except NameError:
  258. portable = False
  259. if param[0] == 'headless':
  260. if param[2].lower() == 'true':
  261. self.cmd_line_headless = 1
  262. else:
  263. self.cmd_line_headless = None
  264. except Exception as e:
  265. log.debug('App.__init__() -->%s' % str(e))
  266. return
  267. except FileNotFoundError as e:
  268. log.debug(str(e))
  269. pass
  270. if portable is False:
  271. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  272. else:
  273. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  274. self.os = 'windows'
  275. else: # Linux/Unix/MacOS
  276. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  277. self.os = 'unix'
  278. # ############################################################################################################
  279. # ################################# Setup folders and files ##################################################
  280. # ############################################################################################################
  281. if not os.path.exists(self.data_path):
  282. os.makedirs(self.data_path)
  283. App.log.debug('Created data folder: ' + self.data_path)
  284. os.makedirs(os.path.join(self.data_path, 'preprocessors'))
  285. App.log.debug('Created data preprocessors folder: ' + os.path.join(self.data_path, 'preprocessors'))
  286. self.preprocessorpaths = os.path.join(self.data_path, 'preprocessors')
  287. if not os.path.exists(self.preprocessorpaths):
  288. os.makedirs(self.preprocessorpaths)
  289. App.log.debug('Created preprocessors folder: ' + self.preprocessorpaths)
  290. # create geo_tools_db.FlatDB file if there is none
  291. try:
  292. f = open(self.data_path + '/geo_tools_db.FlatDB')
  293. f.close()
  294. except IOError:
  295. App.log.debug('Creating empty geo_tool_db.FlatDB')
  296. f = open(self.data_path + '/geo_tools_db.FlatDB', 'w')
  297. json.dump({}, f)
  298. f.close()
  299. # create current_defaults.FlatConfig file if there is none
  300. try:
  301. f = open(self.data_path + '/current_defaults.FlatConfig')
  302. f.close()
  303. except IOError:
  304. App.log.debug('Creating empty current_defaults.FlatConfig')
  305. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  306. json.dump({}, f)
  307. f.close()
  308. # Write factory_defaults.FlatConfig file to disk
  309. FlatCAMDefaults.save_factory_defaults(os.path.join(self.data_path, "factory_defaults.FlatConfig"))
  310. # create a recent files json file if there is none
  311. try:
  312. f = open(self.data_path + '/recent.json')
  313. f.close()
  314. except IOError:
  315. App.log.debug('Creating empty recent.json')
  316. f = open(self.data_path + '/recent.json', 'w')
  317. json.dump([], f)
  318. f.close()
  319. # create a recent projects json file if there is none
  320. try:
  321. fp = open(self.data_path + '/recent_projects.json')
  322. fp.close()
  323. except IOError:
  324. App.log.debug('Creating empty recent_projects.json')
  325. fp = open(self.data_path + '/recent_projects.json', 'w')
  326. json.dump([], fp)
  327. fp.close()
  328. # Application directory. CHDIR to it. Otherwise, trying to load GUI icons will fail as their path is relative.
  329. # This will fail under cx_freeze ...
  330. self.app_home = os.path.dirname(os.path.realpath(__file__))
  331. log.debug("Application path is " + self.app_home)
  332. log.debug("Started in " + os.getcwd())
  333. # cx_freeze workaround
  334. if os.path.isfile(self.app_home):
  335. self.app_home = os.path.dirname(self.app_home)
  336. os.chdir(self.app_home)
  337. # ############################################################################################################
  338. # ################################# DEFAULTS - PREFERENCES STORAGE ###########################################
  339. # ############################################################################################################
  340. self.defaults = FlatCAMDefaults()
  341. self.defaults["root_folder_path"] = self.app_home
  342. current_defaults_path = os.path.join(self.data_path, "current_defaults.FlatConfig")
  343. if user_defaults:
  344. self.defaults.load(filename=current_defaults_path)
  345. if self.defaults['units'] == 'MM':
  346. self.decimals = int(self.defaults['decimals_metric'])
  347. else:
  348. self.decimals = int(self.defaults['decimals_inch'])
  349. if self.defaults["global_gray_icons"] is False:
  350. self.resource_location = 'assets/resources'
  351. else:
  352. self.resource_location = 'assets/resources/dark_resources'
  353. self.current_units = self.defaults['units']
  354. # ###########################################################################################################
  355. # #################################### SETUP OBJECT CLASSES #################################################
  356. # ###########################################################################################################
  357. self.setup_obj_classes()
  358. # ###########################################################################################################
  359. # ###################################### CREATE MULTIPROCESSING POOL #######################################
  360. # ###########################################################################################################
  361. self.pool = Pool()
  362. # ###########################################################################################################
  363. # ###################################### Setting the Splash Screen ##########################################
  364. # ###########################################################################################################
  365. splash_settings = QSettings("Open Source", "FlatCAM")
  366. if splash_settings.contains("splash_screen"):
  367. show_splash = splash_settings.value("splash_screen")
  368. else:
  369. splash_settings.setValue('splash_screen', 1)
  370. # This will write the setting to the platform specific storage.
  371. del splash_settings
  372. show_splash = 1
  373. if show_splash and self.cmd_line_headless != 1:
  374. splash_pix = QtGui.QPixmap(self.resource_location + '/splash.png')
  375. self.splash = QtWidgets.QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
  376. # self.splash.setMask(splash_pix.mask())
  377. # move splashscreen to the current monitor
  378. desktop = QtWidgets.QApplication.desktop()
  379. screen = desktop.screenNumber(QtGui.QCursor.pos())
  380. current_screen_center = desktop.availableGeometry(screen).center()
  381. self.splash.move(current_screen_center - self.splash.rect().center())
  382. self.splash.show()
  383. self.splash.showMessage(_("FlatCAM is initializing ..."),
  384. alignment=Qt.AlignBottom | Qt.AlignLeft,
  385. color=QtGui.QColor("gray"))
  386. else:
  387. show_splash = 0
  388. # ###########################################################################################################
  389. # ######################################### Initialize GUI ##################################################
  390. # ###########################################################################################################
  391. # FlatCAM colors used in plotting
  392. self.FC_light_green = '#BBF268BF'
  393. self.FC_dark_green = '#006E20BF'
  394. self.FC_light_blue = '#a5a5ffbf'
  395. self.FC_dark_blue = '#0000ffbf'
  396. theme_settings = QtCore.QSettings("Open Source", "FlatCAM")
  397. if theme_settings.contains("theme"):
  398. theme = theme_settings.value('theme', type=str)
  399. else:
  400. theme = 'white'
  401. if self.defaults["global_cursor_color_enabled"]:
  402. self.cursor_color_3D = self.defaults["global_cursor_color"]
  403. else:
  404. if theme == 'white':
  405. self.cursor_color_3D = 'black'
  406. else:
  407. self.cursor_color_3D = 'gray'
  408. # update the defaults dict with the setting in QSetting
  409. self.defaults['global_theme'] = theme
  410. self.ui = MainGUI(self)
  411. # set FlatCAM units in the Status bar
  412. self.set_screen_units(self.defaults['units'])
  413. # ###########################################################################################################
  414. # ########################################### AUTOSAVE SETUP ################################################
  415. # ###########################################################################################################
  416. self.block_autosave = False
  417. self.autosave_timer = QtCore.QTimer(self)
  418. self.save_project_auto_update()
  419. self.autosave_timer.timeout.connect(self.save_project_auto)
  420. # ###########################################################################################################
  421. # #################################### LOAD PREPROCESSORS ###################################################
  422. # ###########################################################################################################
  423. # ----------------------------------------- WARNING --------------------------------------------------------
  424. # Preprocessors need to be loaded before the Preferences Manager builds the Preferences
  425. # That's because the number of preprocessors can vary and here the comboboxes are populated
  426. # -----------------------------------------------------------------------------------------------------------
  427. # a dictionary that have as keys the name of the preprocessor files and the value is the class from
  428. # the preprocessor file
  429. self.preprocessors = load_preprocessors(self)
  430. # make sure that always the 'default' preprocessor is the first item in the dictionary
  431. if 'default' in self.preprocessors.keys():
  432. new_ppp_dict = {}
  433. # add the 'default' name first in the dict after removing from the preprocessor's dictionary
  434. default_pp = self.preprocessors.pop('default')
  435. new_ppp_dict['default'] = default_pp
  436. # then add the rest of the keys
  437. for name, val_class in self.preprocessors.items():
  438. new_ppp_dict[name] = val_class
  439. # and now put back the ordered dict with 'default' key first
  440. self.preprocessors = new_ppp_dict
  441. for name in list(self.preprocessors.keys()):
  442. # 'Paste' preprocessors are to be used only in the Solder Paste Dispensing Tool
  443. if name.partition('_')[0] == 'Paste':
  444. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  445. continue
  446. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  447. # HPGL preprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  448. if name == 'hpgl':
  449. continue
  450. self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  451. # ###########################################################################################################
  452. # ##################################### UPDATE PREFERENCES GUI FORMS ########################################
  453. # ###########################################################################################################
  454. self.preferencesUiManager = PreferencesUIManager(defaults=self.defaults, data_path=self.data_path, ui=self.ui,
  455. inform=self.inform)
  456. self.preferencesUiManager.defaults_write_form()
  457. # When the self.defaults dictionary changes will update the Preferences GUI forms
  458. self.defaults.set_change_callback(self.on_defaults_dict_change)
  459. # ###########################################################################################################
  460. # ##################################### FIRST RUN SECTION ###################################################
  461. # ################################ It's done only once after install #####################################
  462. # ###########################################################################################################
  463. if self.defaults["first_run"] is True:
  464. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'COMPACT'
  465. initial_lay = 'minimal'
  466. self.ui.general_defaults_form.general_gui_group.on_layout(lay=initial_lay)
  467. # Set the combobox in Preferences to the current layout
  468. idx = self.ui.general_defaults_form.general_gui_group.layout_combo.findText(initial_lay)
  469. self.ui.general_defaults_form.general_gui_group.layout_combo.setCurrentIndex(idx)
  470. # after the first run, this object should be False
  471. self.defaults["first_run"] = False
  472. self.preferencesUiManager.save_defaults(silent=True)
  473. # ###########################################################################################################
  474. # ############################################ Data #########################################################
  475. # ###########################################################################################################
  476. self.recent = []
  477. self.recent_projects = []
  478. self.clipboard = QtWidgets.QApplication.clipboard()
  479. self.project_filename = None
  480. self.toggle_units_ignore = False
  481. # ###########################################################################################################
  482. # ########################################## LOAD LANGUAGES ################################################
  483. # ###########################################################################################################
  484. self.languages = fcTranslate.load_languages()
  485. for name in sorted(self.languages.values()):
  486. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  487. # ###########################################################################################################
  488. # ####################################### APPLY APP LANGUAGE ################################################
  489. # ###########################################################################################################
  490. ret_val = fcTranslate.apply_language('strings')
  491. if ret_val == "no language":
  492. self.inform.emit('[ERROR] %s' % _("Could not find the Language files. The App strings are missing."))
  493. log.debug("Could not find the Language files. The App strings are missing.")
  494. else:
  495. # make the current language the current selection on the language combobox
  496. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  497. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  498. # ###########################################################################################################
  499. # ###################################### CREATE UNIQUE SERIAL NUMBER ########################################
  500. # ###########################################################################################################
  501. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  502. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  503. self.defaults['global_serial'] = ''.join([random.choice(chars) for __ in range(20)])
  504. self.preferencesUiManager.save_defaults(silent=True, first_time=True)
  505. self.defaults.propagate_defaults()
  506. # ###########################################################################################################
  507. # ######################################## UPDATE THE OPTIONS ###############################################
  508. # ###########################################################################################################
  509. self.options = LoudDict()
  510. # -----------------------------------------------------------------------------------------------------------
  511. # Update the self.options from the self.defaults
  512. # The self.defaults holds the application defaults while the self.options holds the object defaults
  513. # -----------------------------------------------------------------------------------------------------------
  514. # Copy app defaults to project options
  515. for def_key, def_val in self.defaults.items():
  516. self.options[def_key] = deepcopy(def_val)
  517. self.preferencesUiManager.show_preferences_gui()
  518. # ### End of Data ####
  519. # ###########################################################################################################
  520. # #################################### SETUP OBJECT COLLECTION ##############################################
  521. # ###########################################################################################################
  522. self.collection = ObjectCollection(app=self)
  523. self.ui.project_tab_layout.addWidget(self.collection.view)
  524. self.app_obj = AppObject(app=self)
  525. # ### Adjust tabs width ## ##
  526. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  527. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  528. self.collection.view.setMinimumWidth(290)
  529. self.log.debug("Finished creating Object Collection.")
  530. # ###########################################################################################################
  531. # ######################################## SETUP Plot Area ##################################################
  532. # ###########################################################################################################
  533. # determine if the Legacy Graphic Engine is to be used or the OpenGL one
  534. if self.defaults["global_graphic_engine"] == '3D':
  535. self.is_legacy = False
  536. else:
  537. self.is_legacy = True
  538. # Event signals disconnect id holders
  539. self.mp = None
  540. self.mm = None
  541. self.mr = None
  542. self.mdc = None
  543. self.mp_zc = None
  544. self.kp = None
  545. # Matplotlib axis
  546. self.axes = None
  547. if show_splash:
  548. self.splash.showMessage(_("FlatCAM is initializing ...\n"
  549. "Canvas initialization started."),
  550. alignment=Qt.AlignBottom | Qt.AlignLeft,
  551. color=QtGui.QColor("gray"))
  552. start_plot_time = time.time() # debug
  553. self.plotcanvas = None
  554. self.app_cursor = None
  555. self.hover_shapes = None
  556. self.log.debug("Setting up canvas: %s" % str(self.defaults["global_graphic_engine"]))
  557. # setup the PlotCanvas
  558. self.on_plotcanvas_setup()
  559. end_plot_time = time.time()
  560. self.used_time = end_plot_time - start_plot_time
  561. self.log.debug("Finished Canvas initialization in %s seconds." % str(self.used_time))
  562. if show_splash:
  563. self.splash.showMessage('%s: %ssec' % (_("FlatCAM is initializing ...\n"
  564. "Canvas initialization started.\n"
  565. "Canvas initialization finished in"), '%.2f' % self.used_time),
  566. alignment=Qt.AlignBottom | Qt.AlignLeft,
  567. color=QtGui.QColor("gray"))
  568. self.ui.splitter.setStretchFactor(1, 2)
  569. # ###########################################################################################################
  570. # ############################################### SYS TRAY ##################################################
  571. # ###########################################################################################################
  572. if self.defaults["global_systray_icon"]:
  573. self.parent_w = QtWidgets.QWidget()
  574. if self.cmd_line_headless == 1:
  575. self.trayIcon = FlatCAMSystemTray(app=self,
  576. icon=QtGui.QIcon(self.resource_location +
  577. '/flatcam_icon32_green.png'),
  578. headless=True,
  579. parent=self.parent_w)
  580. else:
  581. self.trayIcon = FlatCAMSystemTray(app=self,
  582. icon=QtGui.QIcon(self.resource_location +
  583. '/flatcam_icon32_green.png'),
  584. parent=self.parent_w)
  585. # ###########################################################################################################
  586. # ############################################### Worker SETUP ##############################################
  587. # ###########################################################################################################
  588. if self.defaults["global_worker_number"]:
  589. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  590. else:
  591. self.workers = WorkerStack(workers_number=2)
  592. self.worker_task.connect(self.workers.add_task)
  593. self.log.debug("Finished creating Workers crew.")
  594. # ###########################################################################################################
  595. # ############################################# Activity Monitor ###########################################
  596. # ###########################################################################################################
  597. self.activity_view = FlatCAMActivityView(app=self)
  598. self.ui.infobar.addWidget(self.activity_view)
  599. self.proc_container = FCVisibleProcessContainer(self.activity_view)
  600. # ###########################################################################################################
  601. # ############################################# Signal handling #############################################
  602. # ###########################################################################################################
  603. # ########################################## Custom signals ################################################
  604. # signal for displaying messages in status bar
  605. self.inform[str].connect(self.info)
  606. self.inform[str, bool].connect(self.info)
  607. # signal to be called when the app is quiting
  608. self.app_quit.connect(self.quit_application, type=Qt.QueuedConnection)
  609. self.message.connect(lambda: message_dialog(parent=self.ui))
  610. # self.progress.connect(self.set_progress_bar)
  611. # signals emitted when file state change
  612. self.file_opened.connect(self.register_recent)
  613. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  614. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  615. # ########################################## Standard signals ###############################################
  616. # ### Menu
  617. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  618. self.ui.menufilenewgeo.triggered.connect(self.app_obj.new_geometry_object)
  619. self.ui.menufilenewgrb.triggered.connect(self.app_obj.new_gerber_object)
  620. self.ui.menufilenewexc.triggered.connect(self.app_obj.new_excellon_object)
  621. self.ui.menufilenewdoc.triggered.connect(self.app_obj.new_document_object)
  622. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  623. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  624. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  625. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  626. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  627. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  628. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  629. self.ui.menufileopenscriptexample.triggered.connect(self.on_fileopenscript_example)
  630. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  631. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  632. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  633. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  634. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  635. self.ui.menufileimport_hpgl2_as_geo.triggered.connect(self.on_fileopenhpgl2)
  636. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  637. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  638. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  639. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  640. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  641. self.ui.menufile_print.triggered.connect(lambda: self.on_file_save_objects_pdf(use_thread=True))
  642. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  643. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  644. # self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  645. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  646. self.ui.menufileexportpref.triggered.connect(self.on_export_preferences)
  647. self.ui.menufileimportpref.triggered.connect(self.on_import_preferences)
  648. self.ui.menufile_exit.triggered.connect(self.final_save)
  649. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  650. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  651. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  652. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  653. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  654. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  655. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  656. self.ui.menueditdelete.triggered.connect(self.on_delete)
  657. self.ui.menueditcopyobject.triggered.connect(self.on_copy_command)
  658. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  659. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  660. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  661. self.ui.menuedit_move2origin.triggered.connect(self.on_move2origin)
  662. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  663. self.ui.menueditlocate.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  664. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  665. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  666. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  667. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  668. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  669. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  670. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  671. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  672. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  673. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  674. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  675. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  676. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  677. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  678. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  679. self.ui.menuoptions_tools_db.triggered.connect(lambda: self.on_tools_database(source='app'))
  680. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  681. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  682. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  683. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  684. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  685. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  686. self.ui.menuview_replot.triggered.connect(self.plot_all)
  687. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  688. self.ui.menuview_toggle_fscreen.triggered.connect(self.ui.on_fullscreen)
  689. self.ui.menuview_toggle_parea.triggered.connect(self.ui.on_toggle_plotarea)
  690. self.ui.menuview_toggle_notebook.triggered.connect(self.ui.on_toggle_notebook)
  691. self.ui.menu_toggle_nb.triggered.connect(self.ui.on_toggle_notebook)
  692. self.ui.menuview_toggle_grid.triggered.connect(self.ui.on_toggle_grid)
  693. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_toggle)
  694. self.ui.menuview_toggle_grid_lines.triggered.connect(self.plotcanvas.on_toggle_grid_lines)
  695. self.ui.menuview_toggle_axis.triggered.connect(self.plotcanvas.on_toggle_axis)
  696. self.ui.menuview_toggle_hud.triggered.connect(self.plotcanvas.on_toggle_hud)
  697. self.ui.menutoolshell.triggered.connect(self.ui.toggle_shell_ui)
  698. self.ui.menuhelp_about.triggered.connect(self.on_about)
  699. self.ui.menuhelp_readme.triggered.connect(self.on_readme)
  700. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  701. self.ui.menuhelp_report_bug.triggered.connect(lambda: webbrowser.open(self.bug_report_url))
  702. self.ui.menuhelp_exc_spec.triggered.connect(lambda: webbrowser.open(self.excellon_spec_url))
  703. self.ui.menuhelp_gerber_spec.triggered.connect(lambda: webbrowser.open(self.gerber_spec_url))
  704. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  705. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  706. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  707. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  708. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  709. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  710. self.ui.menuprojectcopy.triggered.connect(self.on_copy_command)
  711. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  712. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  713. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  714. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  715. # ToolBar signals
  716. self.connect_toolbar_signals()
  717. # Notebook and Plot Tab Area signals
  718. # make the right click on the notebook tab and plot tab area tab raise a menu
  719. self.ui.notebook.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  720. self.ui.plot_tab_area.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  721. self.on_tab_setup_context_menu()
  722. # activate initial state
  723. self.on_tab_rmb_click(self.defaults["global_tabs_detachable"])
  724. # Context Menu
  725. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  726. self.ui.popmenu_panel_toggle.triggered.connect(self.ui.on_toggle_notebook)
  727. self.ui.popmenu_new_geo.triggered.connect(self.app_obj.new_geometry_object)
  728. self.ui.popmenu_new_grb.triggered.connect(self.app_obj.new_gerber_object)
  729. self.ui.popmenu_new_exc.triggered.connect(self.app_obj.new_excellon_object)
  730. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  731. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  732. self.ui.clearplot.triggered.connect(self.clear_plots)
  733. self.ui.replot.triggered.connect(self.plot_all)
  734. self.ui.popmenu_copy.triggered.connect(self.on_copy_command)
  735. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  736. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  737. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  738. self.ui.popmenu_move.triggered.connect(self.obj_move)
  739. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  740. # Project Context Menu -> Color Setting
  741. for act in self.ui.menuprojectcolor.actions():
  742. act.triggered.connect(self.on_set_color_action_triggered)
  743. # ###########################################################################################################
  744. # #################################### GUI PREFERENCES SIGNALS ##############################################
  745. # ###########################################################################################################
  746. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  747. lambda: self.on_toggle_units(no_pref=False))
  748. # ##################################### Workspace Setting Signals ###########################################
  749. self.ui.general_defaults_form.general_app_set_group.wk_cb.currentIndexChanged.connect(
  750. self.on_workspace_modified)
  751. self.ui.general_defaults_form.general_app_set_group.wk_orientation_radio.activated_custom.connect(
  752. self.on_workspace_modified
  753. )
  754. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  755. # ###########################################################################################################
  756. # ######################################## GUI SETTINGS SIGNALS #############################################
  757. # ###########################################################################################################
  758. self.ui.general_defaults_form.general_app_set_group.cursor_radio.activated_custom.connect(self.on_cursor_type)
  759. # ######################################## Tools related signals ############################################
  760. # portability changed signal
  761. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  762. # Object list
  763. self.object_status_changed.connect(self.collection.on_collection_updated)
  764. # when there are arguments at application startup this get launched
  765. self.args_at_startup[list].connect(self.on_startup_args)
  766. # ###########################################################################################################
  767. # ####################################### FILE ASSOCIATIONS SIGNALS #########################################
  768. # ###########################################################################################################
  769. self.ui.util_defaults_form.fa_excellon_group.restore_btn.clicked.connect(
  770. lambda: self.restore_extensions(ext_type='excellon'))
  771. self.ui.util_defaults_form.fa_gcode_group.restore_btn.clicked.connect(
  772. lambda: self.restore_extensions(ext_type='gcode'))
  773. self.ui.util_defaults_form.fa_gerber_group.restore_btn.clicked.connect(
  774. lambda: self.restore_extensions(ext_type='gerber'))
  775. self.ui.util_defaults_form.fa_excellon_group.del_all_btn.clicked.connect(
  776. lambda: self.delete_all_extensions(ext_type='excellon'))
  777. self.ui.util_defaults_form.fa_gcode_group.del_all_btn.clicked.connect(
  778. lambda: self.delete_all_extensions(ext_type='gcode'))
  779. self.ui.util_defaults_form.fa_gerber_group.del_all_btn.clicked.connect(
  780. lambda: self.delete_all_extensions(ext_type='gerber'))
  781. self.ui.util_defaults_form.fa_excellon_group.add_btn.clicked.connect(
  782. lambda: self.add_extension(ext_type='excellon'))
  783. self.ui.util_defaults_form.fa_gcode_group.add_btn.clicked.connect(
  784. lambda: self.add_extension(ext_type='gcode'))
  785. self.ui.util_defaults_form.fa_gerber_group.add_btn.clicked.connect(
  786. lambda: self.add_extension(ext_type='gerber'))
  787. self.ui.util_defaults_form.fa_excellon_group.del_btn.clicked.connect(
  788. lambda: self.del_extension(ext_type='excellon'))
  789. self.ui.util_defaults_form.fa_gcode_group.del_btn.clicked.connect(
  790. lambda: self.del_extension(ext_type='gcode'))
  791. self.ui.util_defaults_form.fa_gerber_group.del_btn.clicked.connect(
  792. lambda: self.del_extension(ext_type='gerber'))
  793. # connect the 'Apply' buttons from the Preferences/File Associations
  794. self.ui.util_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  795. lambda: self.on_register_files(obj_type='excellon'))
  796. self.ui.util_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  797. lambda: self.on_register_files(obj_type='gcode'))
  798. self.ui.util_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  799. lambda: self.on_register_files(obj_type='gerber'))
  800. # ###########################################################################################################
  801. # ########################################### KEYWORDS SIGNALS ##############################################
  802. # ###########################################################################################################
  803. self.ui.util_defaults_form.kw_group.restore_btn.clicked.connect(
  804. lambda: self.restore_extensions(ext_type='keyword'))
  805. self.ui.util_defaults_form.kw_group.del_all_btn.clicked.connect(
  806. lambda: self.delete_all_extensions(ext_type='keyword'))
  807. self.ui.util_defaults_form.kw_group.add_btn.clicked.connect(
  808. lambda: self.add_extension(ext_type='keyword'))
  809. self.ui.util_defaults_form.kw_group.del_btn.clicked.connect(
  810. lambda: self.del_extension(ext_type='keyword'))
  811. # ###########################################################################################################
  812. # ########################################### GUI SIGNALS ###################################################
  813. # ###########################################################################################################
  814. self.ui.hud_label.clicked.connect(self.plotcanvas.on_toggle_hud)
  815. self.ui.axis_status_label.clicked.connect(self.plotcanvas.on_toggle_axis)
  816. # ###########################################################################################################
  817. # ####################################### VARIOUS SIGNALS ###################################################
  818. # ###########################################################################################################
  819. # connect the abort_all_tasks related slots to the related signals
  820. self.proc_container.idle_flag.connect(self.app_is_idle)
  821. # signal emitted when a tab is closed in the Plot Area
  822. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_plot_area_tab_closed)
  823. # signal to close the application
  824. self.close_app_signal.connect(self.kill_app)
  825. # ################################# FINISHED CONNECTING SIGNALS #############################################
  826. # ###########################################################################################################
  827. # ###########################################################################################################
  828. # ###########################################################################################################
  829. self.log.debug("Finished connecting Signals.")
  830. # ###########################################################################################################
  831. # ########################################## Other setups ###################################################
  832. # ###########################################################################################################
  833. # to use for tools like Distance tool who depends on the event sources who are changed inside the AppEditors
  834. # depending on from where those tools are called different actions can be done
  835. self.call_source = 'app'
  836. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  837. self.tool_tab_locked = False
  838. # decide if to show or hide the Notebook side of the screen at startup
  839. if self.defaults["global_project_at_startup"] is True:
  840. self.ui.splitter.setSizes([1, 1])
  841. else:
  842. self.ui.splitter.setSizes([0, 1])
  843. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  844. self.setup_component_editor()
  845. # ###########################################################################################################
  846. # ####################################### Auto-complete KEYWORDS ############################################
  847. # ###########################################################################################################
  848. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  849. 'aligndrill', 'aligndrillgrid', 'bbox', 'clear', 'cncjob', 'cutout',
  850. 'del', 'drillcncjob', 'export_dxf', 'edxf', 'export_excellon',
  851. 'export_exc',
  852. 'export_gcode', 'export_gerber', 'export_svg', 'ext', 'exteriors', 'follow',
  853. 'geo_union', 'geocutout', 'get_bounds', 'get_names', 'get_path', 'get_sys', 'help',
  854. 'interiors', 'isolate', 'join_excellon',
  855. 'join_geometry', 'list_sys', 'milld', 'mills', 'milldrills', 'millslots',
  856. 'mirror', 'ncc',
  857. 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  858. 'open_dxf', 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'open_svg',
  859. 'options', 'origin',
  860. 'paint', 'panelize', 'plot_all', 'plot_objects', 'plot_status', 'quit_flatcam',
  861. 'save', 'save_project',
  862. 'save_sys', 'scale', 'set_active', 'set_origin', 'set_path', 'set_sys',
  863. 'skew', 'subtract_poly', 'subtract_rectangle',
  864. 'version', 'write_gcode'
  865. ]
  866. self.default_keywords = ['Desktop', 'Documents', 'FlatConfig', 'FlatPrj', 'False', 'Marius', 'My Documents',
  867. 'Paste_1',
  868. 'Repetier', 'Roland_MDX_20', 'Users', 'Toolchange_Custom', 'Toolchange_Probe_MACH3',
  869. 'Toolchange_manual', 'True', 'Users',
  870. 'all', 'auto', 'axis',
  871. 'axisoffset', 'box', 'center_x', 'center_y', 'columns', 'combine', 'connect',
  872. 'contour', 'default',
  873. 'depthperpass', 'dia', 'diatol', 'dist', 'drilled_dias', 'drillz', 'dpp',
  874. 'dwelltime', 'extracut_length', 'endxy', 'enz', 'f', 'feedrate',
  875. 'feedrate_z', 'grbl_11', 'GRBL_laser', 'gridoffsety', 'gridx', 'gridy',
  876. 'has_offset', 'holes', 'hpgl', 'iso_type', 'line_xyz', 'margin', 'marlin', 'method',
  877. 'milled_dias', 'minoffset', 'name', 'offset', 'opt_type', 'order',
  878. 'outname', 'overlap', 'passes', 'postamble', 'pp', 'ppname_e', 'ppname_g',
  879. 'preamble', 'radius', 'ref', 'rest', 'rows', 'shellvar_', 'scale_factor',
  880. 'spacing_columns',
  881. 'spacing_rows', 'spindlespeed', 'startz', 'startxy',
  882. 'toolchange_xy', 'toolchangez', 'travelz',
  883. 'tooldia', 'use_threads', 'value',
  884. 'x', 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  885. ]
  886. self.tcl_keywords = [
  887. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  888. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  889. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  890. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  891. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  892. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  893. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  894. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  895. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  896. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  897. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  898. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  899. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  900. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  901. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  902. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  903. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  904. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  905. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  906. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  907. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  908. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  909. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  910. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  911. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  912. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  913. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  914. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  915. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  916. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  917. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  918. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  919. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  920. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  921. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  922. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  923. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  924. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  925. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  926. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  927. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  928. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  929. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  930. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  931. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  932. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  933. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  934. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  935. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  936. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  937. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  938. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  939. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  940. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  941. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  942. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  943. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  944. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  945. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  946. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  947. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  948. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  949. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  950. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  951. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  952. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  953. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  954. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  955. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  956. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  957. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  958. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  959. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  960. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  961. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  962. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  963. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  964. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  965. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  966. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  967. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  968. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  969. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  970. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  971. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  972. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  973. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  974. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  975. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  976. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  977. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  978. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  979. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  980. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  981. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  982. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  983. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  984. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  985. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  986. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  987. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  988. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  989. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  990. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  991. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  992. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  993. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  994. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  995. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  996. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  997. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  998. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  999. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  1000. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  1001. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  1002. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  1003. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  1004. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  1005. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  1006. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  1007. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  1008. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  1009. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  1010. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  1011. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  1012. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  1013. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  1014. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  1015. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  1016. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  1017. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  1018. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  1019. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  1020. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  1021. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  1022. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  1023. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  1024. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  1025. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  1026. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  1027. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  1028. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  1029. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  1030. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  1031. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  1032. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  1033. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  1034. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  1035. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  1036. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  1037. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  1038. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  1039. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  1040. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  1041. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  1042. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  1043. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  1044. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  1045. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  1046. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  1047. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  1048. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  1049. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  1050. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  1051. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  1052. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  1053. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  1054. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  1055. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  1056. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  1057. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  1058. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  1059. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  1060. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  1061. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  1062. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  1063. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  1064. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  1065. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  1066. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  1067. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  1068. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  1069. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  1070. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  1071. ]
  1072. self.autocomplete_kw_list = self.defaults['util_autocomplete_keywords'].replace(' ', '').split(',')
  1073. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  1074. # ###########################################################################################################
  1075. # ############################################## Shell SETUP ################################################
  1076. # ###########################################################################################################
  1077. self.shell = FCShell(app=self, version=self.version)
  1078. self.ui.shell_dock.setWidget(self.shell)
  1079. self.log.debug("TCL Shell has been initialized.")
  1080. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  1081. if self.defaults["global_shell_at_startup"]:
  1082. self.ui.shell_dock.show()
  1083. else:
  1084. self.ui.shell_dock.hide()
  1085. # ###########################################################################################################
  1086. # ########################################## Tools and Plugins ##############################################
  1087. # ###########################################################################################################
  1088. self.dblsidedtool = None
  1089. self.distance_tool = None
  1090. self.distance_min_tool = None
  1091. self.panelize_tool = None
  1092. self.film_tool = None
  1093. self.paste_tool = None
  1094. self.calculator_tool = None
  1095. self.rules_tool = None
  1096. self.sub_tool = None
  1097. self.move_tool = None
  1098. self.cutout_tool = None
  1099. self.ncclear_tool = None
  1100. self.paint_tool = None
  1101. self.isolation_tool = None
  1102. self.optimal_tool = None
  1103. self.transform_tool = None
  1104. self.properties_tool = None
  1105. self.pdf_tool = None
  1106. self.image_tool = None
  1107. self.pcb_wizard_tool = None
  1108. self.cal_exc_tool = None
  1109. self.qrcode_tool = None
  1110. self.copper_thieving_tool = None
  1111. self.fiducial_tool = None
  1112. self.edrills_tool = None
  1113. self.align_objects_tool = None
  1114. self.punch_tool = None
  1115. self.invert_tool = None
  1116. self.corners_tool = None
  1117. self.etch_tool = None
  1118. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  1119. try:
  1120. self.install_tools()
  1121. except AttributeError as e:
  1122. log.debug("App.__init__() install_tools() --> %s" % str(e))
  1123. # ###########################################################################################################
  1124. # ############################################ SETUP RECENT ITEMS ###########################################
  1125. # ###########################################################################################################
  1126. self.setup_recent_items()
  1127. # ###########################################################################################################
  1128. # ######################################### BookMarks Manager ###############################################
  1129. # ###########################################################################################################
  1130. # install Bookmark Manager and populate bookmarks in the Help -> Bookmarks
  1131. self.install_bookmarks()
  1132. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"])
  1133. # ###########################################################################################################
  1134. # ########################################### Tools Database ################################################
  1135. # ###########################################################################################################
  1136. self.tools_db_tab = None
  1137. # ### System Font Parsing ###
  1138. # self.f_parse = ParseFont(self)
  1139. # self.parse_system_fonts()
  1140. # ###########################################################################################################
  1141. # ######################################### Check for updates ###############################################
  1142. # ###########################################################################################################
  1143. # Separate thread (Not worker)
  1144. # Check for updates on startup but only if the user consent and the app is not in Beta version
  1145. if (self.beta is False or self.beta is None) and \
  1146. self.ui.general_defaults_form.general_app_group.version_check_cb.get_value() is True:
  1147. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  1148. # self.thr2 = QtCore.QThread()
  1149. self.worker_task.emit({'fcn': self.version_check,
  1150. 'params': []})
  1151. # self.thr2.start(QtCore.QThread.LowPriority)
  1152. # ###########################################################################################################
  1153. # ##################################### Register files with FlatCAM; #######################################
  1154. # ################################### It works only for Windows for now ####################################
  1155. # ###########################################################################################################
  1156. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  1157. self.on_register_files()
  1158. # ###########################################################################################################
  1159. # ######################################## Variables for global usage #######################################
  1160. # ###########################################################################################################
  1161. # hold the App units
  1162. self.units = 'MM'
  1163. # coordinates for relative position display
  1164. self.rel_point1 = (0, 0)
  1165. self.rel_point2 = (0, 0)
  1166. # variable to store coordinates
  1167. self.pos = (0, 0)
  1168. self.pos_canvas = (0, 0)
  1169. self.pos_jump = (0, 0)
  1170. # variable to store mouse coordinates
  1171. self.mouse = [0, 0]
  1172. # variable to store the delta positions on cavnas
  1173. self.dx = 0
  1174. self.dy = 0
  1175. # decide if we have a double click or single click
  1176. self.doubleclick = False
  1177. # store here the is_dragging value
  1178. self.event_is_dragging = False
  1179. # variable to store if a command is active (then the var is not None) and which one it is
  1180. self.command_active = None
  1181. # variable to store the status of moving selection action
  1182. # None value means that it's not an selection action
  1183. # True value = a selection from left to right
  1184. # False value = a selection from right to left
  1185. self.selection_type = None
  1186. # List to store the objects that are currently loaded in FlatCAM
  1187. # This list is updated on each object creation or object delete
  1188. self.all_objects_list = []
  1189. self.objects_under_the_click_list = []
  1190. # List to store the objects that are selected
  1191. self.sel_objects_list = []
  1192. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  1193. self.key_modifiers = None
  1194. # Variable to store the status of the code editor
  1195. self.toggle_codeeditor = False
  1196. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  1197. self.click_noproject = False
  1198. self.cursor = None
  1199. # Variable to store the GCODE that was edited
  1200. self.gcode_edited = ""
  1201. self.text_editor_tab = None
  1202. # reference for the self.ui.code_editor
  1203. self.reference_code_editor = None
  1204. self.script_code = ''
  1205. # if Tools DB are changed/edited in the Edit -> Tools Database tab the value will be set to True
  1206. self.tools_db_changed_flag = False
  1207. self.grb_list = ['art', 'bot', 'bsm', 'cmp', 'crc', 'crs', 'dim', 'g4', 'gb0', 'gb1', 'gb2', 'gb3', 'gb5',
  1208. 'gb6', 'gb7', 'gb8', 'gb9', 'gbd', 'gbl', 'gbo', 'gbp', 'gbr', 'gbs', 'gdo', 'ger', 'gko',
  1209. 'gml', 'gm1', 'gm2', 'gm3', 'grb', 'gtl', 'gto', 'gtp', 'gts', 'ly15', 'ly2', 'mil', 'outline',
  1210. 'pho', 'plc', 'pls', 'smb', 'smt', 'sol', 'spb', 'spt', 'ssb', 'sst', 'stc', 'sts', 'top',
  1211. 'tsm']
  1212. self.exc_list = ['drd', 'drl', 'drill', 'exc', 'ncd', 'tap', 'txt', 'xln']
  1213. self.gcode_list = ['cnc', 'din', 'dnc', 'ecs', 'eia', 'fan', 'fgc', 'fnc', 'gc', 'gcd', 'gcode', 'h', 'hnc',
  1214. 'i', 'min', 'mpf', 'mpr', 'nc', 'ncc', 'ncg', 'ngc', 'ncp', 'out', 'ply', 'rol',
  1215. 'sbp', 'tap', 'xpi']
  1216. self.svg_list = ['svg']
  1217. self.dxf_list = ['dxf']
  1218. self.pdf_list = ['pdf']
  1219. self.prj_list = ['flatprj']
  1220. self.conf_list = ['flatconfig']
  1221. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1222. # flag for polygons not cleared
  1223. self.poly_not_cleared = False
  1224. # VisPy visuals
  1225. self.isHovering = False
  1226. self.notHovering = True
  1227. # Window geometry
  1228. self.x_pos = None
  1229. self.y_pos = None
  1230. self.width = None
  1231. self.height = None
  1232. # when True, the app has to return from any thread
  1233. self.abort_flag = False
  1234. # set the value used in the Windows Title
  1235. self.engine = self.ui.general_defaults_form.general_app_group.ge_radio.get_value()
  1236. # this holds a widget that is installed in the Plot Area when View Source option is used
  1237. self.source_editor_tab = None
  1238. self.pagesize = {}
  1239. # Storage for shapes, storage that can be used by FlatCAm tools for utility geometry
  1240. # VisPy visuals
  1241. if self.is_legacy is False:
  1242. try:
  1243. self.tool_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  1244. except AttributeError:
  1245. self.tool_shapes = None
  1246. else:
  1247. from AppGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  1248. self.tool_shapes = ShapeCollectionLegacy(obj=self, app=self, name="tool")
  1249. # used in the delayed shutdown self.start_delayed_quit() method
  1250. self.save_timer = None
  1251. # ###########################################################################################################
  1252. # ################################## ADDING FlatCAM EDITORS section #########################################
  1253. # ###########################################################################################################
  1254. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  1255. # at the first launch of the App , the editors will not be functional.
  1256. try:
  1257. self.geo_editor = FlatCAMGeoEditor(self)
  1258. except AttributeError:
  1259. pass
  1260. try:
  1261. self.exc_editor = FlatCAMExcEditor(self)
  1262. except AttributeError:
  1263. pass
  1264. try:
  1265. self.grb_editor = FlatCAMGrbEditor(self)
  1266. except AttributeError:
  1267. pass
  1268. self.log.debug("Finished adding FlatCAM Editor's.")
  1269. self.set_ui_title(name=_("New Project - Not saved"))
  1270. # disable the Excellon path optimizations made with Google OR-Tools if the app is run on a 32bit platform
  1271. current_platform = platform.architecture()[0]
  1272. if current_platform != '64bit':
  1273. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T')
  1274. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.setDisabled(True)
  1275. # ###########################################################################################################
  1276. # ########################################### EXCLUSION AREAS ###############################################
  1277. # ###########################################################################################################
  1278. self.exc_areas = ExclusionAreas(app=self)
  1279. # ###########################################################################################################
  1280. # ##################################### Finished the CONSTRUCTOR ############################################
  1281. # ###########################################################################################################
  1282. App.log.debug("END of constructor. Releasing control.")
  1283. # ###########################################################################################################
  1284. # ########################################## SHOW GUI #######################################################
  1285. # ###########################################################################################################
  1286. # if the app is not started as headless, show it
  1287. if self.cmd_line_headless != 1:
  1288. if show_splash:
  1289. # finish the splash
  1290. self.splash.finish(self.ui)
  1291. mgui_settings = QSettings("Open Source", "FlatCAM")
  1292. if mgui_settings.contains("maximized_gui"):
  1293. maximized_ui = mgui_settings.value('maximized_gui', type=bool)
  1294. if maximized_ui is True:
  1295. self.ui.showMaximized()
  1296. else:
  1297. self.ui.show()
  1298. else:
  1299. self.ui.show()
  1300. if self.defaults["global_systray_icon"]:
  1301. self.trayIcon.show()
  1302. else:
  1303. log.warning("******************* RUNNING HEADLESS *******************")
  1304. # ###########################################################################################################
  1305. # ######################################## START-UP ARGUMENTS ###############################################
  1306. # ###########################################################################################################
  1307. # test if the program was started with a script as parameter
  1308. if self.cmd_line_shellvar:
  1309. try:
  1310. cnt = 0
  1311. command_tcl = 0
  1312. for i in self.cmd_line_shellvar.split(','):
  1313. if i is not None:
  1314. # noinspection PyBroadException
  1315. try:
  1316. command_tcl = eval(i)
  1317. except Exception:
  1318. command_tcl = i
  1319. command_tcl_formatted = 'set shellvar_{nr} "{cmd}"'.format(cmd=str(command_tcl), nr=str(cnt))
  1320. cnt += 1
  1321. # if there are Windows paths then replace the path separator with a Unix like one
  1322. if sys.platform == 'win32':
  1323. command_tcl_formatted = command_tcl_formatted.replace('\\', '/')
  1324. self.shell.exec_command(command_tcl_formatted, no_echo=True)
  1325. except Exception as ext:
  1326. print("ERROR: ", ext)
  1327. sys.exit(2)
  1328. if self.cmd_line_shellfile:
  1329. if self.cmd_line_headless != 1:
  1330. if self.ui.shell_dock.isHidden():
  1331. self.ui.shell_dock.show()
  1332. try:
  1333. with open(self.cmd_line_shellfile, "r") as myfile:
  1334. # if show_splash:
  1335. # self.splash.showMessage('%s: %ssec\n%s' % (
  1336. # _("Canvas initialization started.\n"
  1337. # "Canvas initialization finished in"), '%.2f' % self.used_time,
  1338. # _("Executing Tcl Script ...")),
  1339. # alignment=Qt.AlignBottom | Qt.AlignLeft,
  1340. # color=QtGui.QColor("gray"))
  1341. cmd_line_shellfile_text = myfile.read()
  1342. if self.cmd_line_headless != 1:
  1343. self.shell.exec_command(cmd_line_shellfile_text)
  1344. else:
  1345. self.shell.exec_command(cmd_line_shellfile_text, no_echo=True)
  1346. except Exception as ext:
  1347. print("ERROR: ", ext)
  1348. sys.exit(2)
  1349. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  1350. # the path/file_name must be enclosed in quotes if it contain spaces
  1351. if App.args:
  1352. self.args_at_startup.emit(App.args)
  1353. if self.defaults.old_defaults_found is True:
  1354. self.inform.emit('[WARNING_NOTCL] %s' % _("Found old default preferences files. "
  1355. "Please reboot the application to update."))
  1356. self.defaults.old_defaults_found = False
  1357. # ######################################### INIT FINISHED #######################################################
  1358. # #################################################################################################################
  1359. # #################################################################################################################
  1360. # #################################################################################################################
  1361. # #################################################################################################################
  1362. # #################################################################################################################
  1363. @staticmethod
  1364. def copy_and_overwrite(from_path, to_path):
  1365. """
  1366. From here:
  1367. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  1368. :param from_path: source path
  1369. :param to_path: destination path
  1370. :return: None
  1371. """
  1372. if os.path.exists(to_path):
  1373. shutil.rmtree(to_path)
  1374. try:
  1375. shutil.copytree(from_path, to_path)
  1376. except FileNotFoundError:
  1377. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\AppGUI\\VisPyData\\data'
  1378. shutil.copytree(from_new_path, to_path)
  1379. def on_startup_args(self, args, silent=False):
  1380. """
  1381. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  1382. :param silent: when True it will not print messages on Tcl Shell and/or status bar
  1383. :param args: a list containing the application args at startup
  1384. :return: None
  1385. """
  1386. if args is not None:
  1387. args_to_process = args
  1388. else:
  1389. args_to_process = App.args
  1390. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  1391. for argument in args_to_process:
  1392. if '.FlatPrj'.lower() in argument.lower():
  1393. try:
  1394. project_name = str(argument)
  1395. if project_name == "":
  1396. if silent is False:
  1397. self.inform.emit(_("Cancelled."))
  1398. else:
  1399. # self.open_project(project_name)
  1400. run_from_arg = True
  1401. # self.worker_task.emit({'fcn': self.open_project,
  1402. # 'params': [project_name, run_from_arg]})
  1403. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  1404. except Exception as e:
  1405. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  1406. elif '.FlatConfig'.lower() in argument.lower():
  1407. try:
  1408. file_name = str(argument)
  1409. if file_name == "":
  1410. if silent is False:
  1411. self.inform.emit(_("Open Config file failed."))
  1412. else:
  1413. run_from_arg = True
  1414. # self.worker_task.emit({'fcn': self.open_config_file,
  1415. # 'params': [file_name, run_from_arg]})
  1416. self.open_config_file(file_name, run_from_arg=run_from_arg)
  1417. except Exception as e:
  1418. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  1419. elif '.FlatScript'.lower() in argument.lower() or '.TCL'.lower() in argument.lower():
  1420. try:
  1421. file_name = str(argument)
  1422. if file_name == "":
  1423. if silent is False:
  1424. self.inform.emit(_("Open Script file failed."))
  1425. else:
  1426. if silent is False:
  1427. self.on_fileopenscript(name=file_name)
  1428. self.ui.plot_tab_area.setCurrentWidget(self.ui.plot_tab)
  1429. self.on_filerunscript(name=file_name)
  1430. except Exception as e:
  1431. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  1432. elif 'quit'.lower() in argument.lower() or 'exit'.lower() in argument.lower():
  1433. log.debug("App.on_startup_args() --> Quit event.")
  1434. sys.exit()
  1435. elif 'save'.lower() in argument.lower():
  1436. log.debug("App.on_startup_args() --> Save event. App Defaults saved.")
  1437. self.preferencesUiManager.save_defaults()
  1438. else:
  1439. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  1440. proc_arg = argument.lower()
  1441. for ext in exc_list:
  1442. proc_ext = ext.replace(' ', '')
  1443. proc_ext = '.%s' % proc_ext
  1444. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1445. file_name = str(argument)
  1446. if file_name == "":
  1447. if silent is False:
  1448. self.inform.emit(_("Open Excellon file failed."))
  1449. else:
  1450. self.on_fileopenexcellon(name=file_name, signal=None)
  1451. return
  1452. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  1453. for ext in gco_list:
  1454. proc_ext = ext.replace(' ', '')
  1455. proc_ext = '.%s' % proc_ext
  1456. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1457. file_name = str(argument)
  1458. if file_name == "":
  1459. if silent is False:
  1460. self.inform.emit(_("Open GCode file failed."))
  1461. else:
  1462. self.on_fileopengcode(name=file_name, signal=None)
  1463. return
  1464. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  1465. for ext in grb_list:
  1466. proc_ext = ext.replace(' ', '')
  1467. proc_ext = '.%s' % proc_ext
  1468. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1469. file_name = str(argument)
  1470. if file_name == "":
  1471. if silent is False:
  1472. self.inform.emit(_("Open Gerber file failed."))
  1473. else:
  1474. self.on_fileopengerber(name=file_name, signal=None)
  1475. return
  1476. # if it reached here without already returning then the app was registered with a file that it does not
  1477. # recognize therefore we must quit but take into consideration the app reboot from within, in that case
  1478. # the args_to_process will contain the path to the FlatCAM.exe (cx_freezed executable)
  1479. # for arg in args_to_process:
  1480. # if 'FlatCAM.exe' in arg:
  1481. # continue
  1482. # else:
  1483. # sys.exit(2)
  1484. def set_ui_title(self, name):
  1485. """
  1486. Sets the title of the main window.
  1487. :param name: String that store the project path and project name
  1488. :return: None
  1489. """
  1490. self.ui.setWindowTitle('FlatCAM %s %s - %s - [%s] %s' %
  1491. (self.version,
  1492. ('BETA' if self.beta else ''),
  1493. platform.architecture()[0],
  1494. self.engine,
  1495. name)
  1496. )
  1497. def on_app_restart(self):
  1498. # make sure that the Sys Tray icon is hidden before restart otherwise it will
  1499. # be left in the SySTray
  1500. try:
  1501. self.trayIcon.hide()
  1502. except Exception:
  1503. pass
  1504. fcTranslate.restart_program(app=self)
  1505. def clear_pool(self):
  1506. """
  1507. Clear the multiprocessing pool and calls garbage collector.
  1508. :return: None
  1509. """
  1510. self.pool.close()
  1511. self.pool = Pool()
  1512. self.pool_recreated.emit(self.pool)
  1513. gc.collect()
  1514. def install_tools(self):
  1515. """
  1516. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  1517. Instantiation of the Tools classes.
  1518. The order that the tools are installed is important as they can depend on each other install position.
  1519. :return: None
  1520. """
  1521. self.distance_tool = Distance(self)
  1522. self.distance_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance16.png'), pos=self.ui.menuedit,
  1523. before=self.ui.menueditorigin,
  1524. separator=False)
  1525. self.distance_min_tool = DistanceMin(self)
  1526. self.distance_min_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance_min16.png'),
  1527. pos=self.ui.menuedit,
  1528. before=self.ui.menueditorigin,
  1529. separator=True)
  1530. self.dblsidedtool = DblSidedTool(self)
  1531. self.dblsidedtool.install(icon=QtGui.QIcon(self.resource_location + '/doubleside16.png'), separator=False)
  1532. self.cal_exc_tool = ToolCalibration(self)
  1533. self.cal_exc_tool.install(icon=QtGui.QIcon(self.resource_location + '/calibrate_16.png'), pos=self.ui.menutool,
  1534. before=self.dblsidedtool.menuAction,
  1535. separator=False)
  1536. self.align_objects_tool = AlignObjects(self)
  1537. self.align_objects_tool.install(icon=QtGui.QIcon(self.resource_location + '/align16.png'), separator=False)
  1538. self.edrills_tool = ToolExtractDrills(self)
  1539. self.edrills_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill16.png'), separator=True)
  1540. self.panelize_tool = Panelize(self)
  1541. self.panelize_tool.install(icon=QtGui.QIcon(self.resource_location + '/panelize16.png'))
  1542. self.film_tool = Film(self)
  1543. self.film_tool.install(icon=QtGui.QIcon(self.resource_location + '/film16.png'))
  1544. self.paste_tool = SolderPaste(self)
  1545. self.paste_tool.install(icon=QtGui.QIcon(self.resource_location + '/solderpastebis32.png'))
  1546. self.calculator_tool = ToolCalculator(self)
  1547. self.calculator_tool.install(icon=QtGui.QIcon(self.resource_location + '/calculator16.png'), separator=True)
  1548. self.sub_tool = ToolSub(self)
  1549. self.sub_tool.install(icon=QtGui.QIcon(self.resource_location + '/sub32.png'),
  1550. pos=self.ui.menutool, separator=True)
  1551. self.rules_tool = RulesCheck(self)
  1552. self.rules_tool.install(icon=QtGui.QIcon(self.resource_location + '/rules32.png'),
  1553. pos=self.ui.menutool, separator=False)
  1554. self.optimal_tool = ToolOptimal(self)
  1555. self.optimal_tool.install(icon=QtGui.QIcon(self.resource_location + '/open_excellon32.png'),
  1556. pos=self.ui.menutool, separator=True)
  1557. self.move_tool = ToolMove(self)
  1558. self.move_tool.install(icon=QtGui.QIcon(self.resource_location + '/move16.png'), pos=self.ui.menuedit,
  1559. before=self.ui.menueditorigin, separator=True)
  1560. self.cutout_tool = CutOut(self)
  1561. self.cutout_tool.install(icon=QtGui.QIcon(self.resource_location + '/cut16_bis.png'), pos=self.ui.menutool,
  1562. before=self.sub_tool.menuAction)
  1563. self.ncclear_tool = NonCopperClear(self)
  1564. self.ncclear_tool.install(icon=QtGui.QIcon(self.resource_location + '/ncc16.png'), pos=self.ui.menutool,
  1565. before=self.sub_tool.menuAction, separator=True)
  1566. self.paint_tool = ToolPaint(self)
  1567. self.paint_tool.install(icon=QtGui.QIcon(self.resource_location + '/paint16.png'), pos=self.ui.menutool,
  1568. before=self.sub_tool.menuAction, separator=True)
  1569. self.isolation_tool = ToolIsolation(self)
  1570. self.isolation_tool.install(icon=QtGui.QIcon(self.resource_location + '/iso_16.png'), pos=self.ui.menutool,
  1571. before=self.sub_tool.menuAction, separator=True)
  1572. self.copper_thieving_tool = ToolCopperThieving(self)
  1573. self.copper_thieving_tool.install(icon=QtGui.QIcon(self.resource_location + '/copperfill32.png'),
  1574. pos=self.ui.menutool)
  1575. self.fiducial_tool = ToolFiducials(self)
  1576. self.fiducial_tool.install(icon=QtGui.QIcon(self.resource_location + '/fiducials_32.png'),
  1577. pos=self.ui.menutool)
  1578. self.qrcode_tool = QRCode(self)
  1579. self.qrcode_tool.install(icon=QtGui.QIcon(self.resource_location + '/qrcode32.png'),
  1580. pos=self.ui.menutool)
  1581. self.punch_tool = ToolPunchGerber(self)
  1582. self.punch_tool.install(icon=QtGui.QIcon(self.resource_location + '/punch32.png'), pos=self.ui.menutool)
  1583. self.invert_tool = ToolInvertGerber(self)
  1584. self.invert_tool.install(icon=QtGui.QIcon(self.resource_location + '/invert32.png'), pos=self.ui.menutool)
  1585. self.corners_tool = ToolCorners(self)
  1586. self.corners_tool.install(icon=QtGui.QIcon(self.resource_location + '/corners_32.png'), pos=self.ui.menutool)
  1587. self.etch_tool = ToolEtchCompensation(self)
  1588. self.etch_tool.install(icon=QtGui.QIcon(self.resource_location + '/etch_32.png'), pos=self.ui.menutool)
  1589. self.transform_tool = ToolTransform(self)
  1590. self.transform_tool.install(icon=QtGui.QIcon(self.resource_location + '/transform.png'),
  1591. pos=self.ui.menuoptions, separator=True)
  1592. self.properties_tool = Properties(self)
  1593. self.properties_tool.install(icon=QtGui.QIcon(self.resource_location + '/properties32.png'),
  1594. pos=self.ui.menuoptions)
  1595. self.pdf_tool = ToolPDF(self)
  1596. self.pdf_tool.install(icon=QtGui.QIcon(self.resource_location + '/pdf32.png'),
  1597. pos=self.ui.menufileimport,
  1598. separator=True)
  1599. self.image_tool = ToolImage(self)
  1600. self.image_tool.install(icon=QtGui.QIcon(self.resource_location + '/image32.png'),
  1601. pos=self.ui.menufileimport,
  1602. separator=True)
  1603. self.pcb_wizard_tool = PcbWizard(self)
  1604. self.pcb_wizard_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill32.png'),
  1605. pos=self.ui.menufileimport)
  1606. self.log.debug("Tools are installed.")
  1607. def remove_tools(self):
  1608. """
  1609. Will remove all the actions in the Tool menu.
  1610. :return: None
  1611. """
  1612. for act in self.ui.menutool.actions():
  1613. self.ui.menutool.removeAction(act)
  1614. def init_tools(self):
  1615. """
  1616. Initialize the Tool tab in the notebook side of the central widget.
  1617. Remove the actions in the Tools menu.
  1618. Instantiate again the FlatCAM tools (plugins).
  1619. All this is required when changing the layout: standard, compact etc.
  1620. :return: None
  1621. """
  1622. log.debug("init_tools()")
  1623. # delete the data currently in the Tools Tab and the Tab itself
  1624. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  1625. if widget is not None:
  1626. widget.deleteLater()
  1627. self.ui.notebook.removeTab(2)
  1628. # rebuild the Tools Tab
  1629. self.ui.tool_tab = QtWidgets.QWidget()
  1630. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  1631. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  1632. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  1633. self.ui.tool_scroll_area = VerticalScrollArea()
  1634. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  1635. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  1636. # first remove all of them
  1637. self.remove_tools()
  1638. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  1639. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon(self.resource_location + '/shell16.png'),
  1640. '&Command Line\tS')
  1641. self.ui.menutoolshell.triggered.connect(self.ui.toggle_shell_ui)
  1642. # third install all of them
  1643. try:
  1644. self.install_tools()
  1645. except AttributeError:
  1646. pass
  1647. self.log.debug("Tools are initialized.")
  1648. # def parse_system_fonts(self):
  1649. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  1650. # 'params': []})
  1651. def connect_toolbar_signals(self):
  1652. """
  1653. Reconnect the signals to the actions in the toolbar.
  1654. This has to be done each time after the FlatCAM tools are removed/installed.
  1655. :return: None
  1656. """
  1657. # Toolbar
  1658. # File Toolbar Signals
  1659. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  1660. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  1661. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  1662. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  1663. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  1664. # View Toolbar Signals
  1665. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  1666. self.ui.replot_btn.triggered.connect(self.plot_all)
  1667. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  1668. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  1669. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  1670. # Edit Toolbar Signals
  1671. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  1672. self.ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  1673. self.ui.copy_btn.triggered.connect(self.on_copy_command)
  1674. self.ui.delete_btn.triggered.connect(self.on_delete)
  1675. self.ui.distance_btn.triggered.connect(lambda: self.distance_tool.run(toggle=True))
  1676. self.ui.distance_min_btn.triggered.connect(lambda: self.distance_min_tool.run(toggle=True))
  1677. self.ui.origin_btn.triggered.connect(self.on_set_origin)
  1678. self.ui.move2origin_btn.triggered.connect(self.on_move2origin)
  1679. self.ui.jmp_btn.triggered.connect(self.on_jump_to)
  1680. self.ui.locate_btn.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  1681. # Scripting Toolbar Signals
  1682. self.ui.shell_btn.triggered.connect(self.ui.toggle_shell_ui)
  1683. self.ui.new_script_btn.triggered.connect(self.on_filenewscript)
  1684. self.ui.open_script_btn.triggered.connect(self.on_fileopenscript)
  1685. self.ui.run_script_btn.triggered.connect(self.on_filerunscript)
  1686. # Tools Toolbar Signals
  1687. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  1688. self.ui.cal_btn.triggered.connect(lambda: self.cal_exc_tool.run(toggle=True))
  1689. self.ui.align_btn.triggered.connect(lambda: self.align_objects_tool.run(toggle=True))
  1690. self.ui.extract_btn.triggered.connect(lambda: self.edrills_tool.run(toggle=True))
  1691. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  1692. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  1693. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  1694. self.ui.isolation_btn.triggered.connect(lambda: self.isolation_tool.run(toggle=True))
  1695. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  1696. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  1697. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  1698. self.ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  1699. self.ui.rules_btn.triggered.connect(lambda: self.rules_tool.run(toggle=True))
  1700. self.ui.optimal_btn.triggered.connect(lambda: self.optimal_tool.run(toggle=True))
  1701. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  1702. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  1703. self.ui.qrcode_btn.triggered.connect(lambda: self.qrcode_tool.run(toggle=True))
  1704. self.ui.copperfill_btn.triggered.connect(lambda: self.copper_thieving_tool.run(toggle=True))
  1705. self.ui.fiducials_btn.triggered.connect(lambda: self.fiducial_tool.run(toggle=True))
  1706. self.ui.punch_btn.triggered.connect(lambda: self.punch_tool.run(toggle=True))
  1707. self.ui.invert_btn.triggered.connect(lambda: self.invert_tool.run(toggle=True))
  1708. self.ui.corners_tool_btn.triggered.connect(lambda: self.corners_tool.run(toggle=True))
  1709. self.ui.etch_btn.triggered.connect(lambda: self.etch_tool.run(toggle=True))
  1710. def object2editor(self):
  1711. """
  1712. Send the current Geometry, Gerber, Excellon object or CNCJob (if any) into the it's editor.
  1713. :return: None
  1714. """
  1715. self.defaults.report_usage("object2editor()")
  1716. # disable the objects menu as it may interfere with the AppEditors
  1717. self.ui.menuobjects.setDisabled(True)
  1718. edited_object = self.collection.get_active()
  1719. if isinstance(edited_object, GerberObject) or isinstance(edited_object, GeometryObject) or \
  1720. isinstance(edited_object, ExcellonObject) or isinstance(edited_object, CNCJobObject):
  1721. pass
  1722. else:
  1723. self.inform.emit('[WARNING_NOTCL] %s' % _("Select a Geometry, Gerber, Excellon or CNCJob Object to edit."))
  1724. return
  1725. if isinstance(edited_object, GeometryObject):
  1726. # store the Geometry Editor Toolbar visibility before entering in the Editor
  1727. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  1728. # we set the notebook to hidden
  1729. # self.ui.splitter.setSizes([0, 1])
  1730. if edited_object.multigeo is True:
  1731. sel_rows = [item.row() for item in edited_object.ui.geo_tools_table.selectedItems()]
  1732. if len(sel_rows) > 1:
  1733. self.inform.emit('[WARNING_NOTCL] %s' %
  1734. _("Simultaneous editing of tools geometry in a MultiGeo Geometry "
  1735. "is not possible.\n"
  1736. "Edit only one geometry at a time."))
  1737. # determine the tool dia of the selected tool
  1738. selected_tooldia = float(edited_object.ui.geo_tools_table.item(sel_rows[0], 1).text())
  1739. # now find the key in the edited_object.tools that has this tooldia
  1740. multi_tool = 1
  1741. for tool in edited_object.tools:
  1742. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  1743. multi_tool = tool
  1744. break
  1745. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  1746. else:
  1747. self.geo_editor.edit_fcgeometry(edited_object)
  1748. # set call source to the Editor we go into
  1749. self.call_source = 'geo_editor'
  1750. elif isinstance(edited_object, ExcellonObject):
  1751. # store the Excellon Editor Toolbar visibility before entering in the Editor
  1752. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  1753. if self.ui.splitter.sizes()[0] == 0:
  1754. self.ui.splitter.setSizes([1, 1])
  1755. self.exc_editor.edit_fcexcellon(edited_object)
  1756. # set call source to the Editor we go into
  1757. self.call_source = 'exc_editor'
  1758. elif isinstance(edited_object, GerberObject):
  1759. # store the Gerber Editor Toolbar visibility before entering in the Editor
  1760. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  1761. if self.ui.splitter.sizes()[0] == 0:
  1762. self.ui.splitter.setSizes([1, 1])
  1763. self.grb_editor.edit_fcgerber(edited_object)
  1764. # set call source to the Editor we go into
  1765. self.call_source = 'grb_editor'
  1766. # reset the following variables so the UI is built again after edit
  1767. edited_object.ui_build = False
  1768. edited_object.build_aperture_storage = False
  1769. elif isinstance(edited_object, CNCJobObject):
  1770. if self.ui.splitter.sizes()[0] == 0:
  1771. self.ui.splitter.setSizes([1, 1])
  1772. edited_object.on_edit_code_click()
  1773. return
  1774. # make sure that we can't select another object while in Editor Mode:
  1775. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  1776. self.ui.project_frame.setDisabled(True)
  1777. # delete any selection shape that might be active as they are not relevant in Editor
  1778. self.delete_selection_shape()
  1779. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  1780. self.ui.plot_tab_area.protectTab(0)
  1781. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor is activated ..."))
  1782. self.should_we_save = True
  1783. def editor2object(self, cleanup=None):
  1784. """
  1785. Transfers the Geometry or Excellon from it's editor to the current object.
  1786. :return: None
  1787. """
  1788. self.defaults.report_usage("editor2object()")
  1789. # re-enable the objects menu that was disabled on entry in Editor mode
  1790. self.ui.menuobjects.setDisabled(False)
  1791. # do not update a geometry or excellon object unless it comes out of an editor
  1792. if self.call_source != 'app':
  1793. edited_obj = self.collection.get_active()
  1794. if cleanup is None:
  1795. msgbox = QtWidgets.QMessageBox()
  1796. msgbox.setText(_("Do you want to save the edited object?"))
  1797. msgbox.setWindowTitle(_("Close Editor"))
  1798. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  1799. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  1800. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  1801. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  1802. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  1803. msgbox.setDefaultButton(bt_yes)
  1804. msgbox.exec_()
  1805. response = msgbox.clickedButton()
  1806. if response == bt_yes:
  1807. # clean the Tools Tab
  1808. self.ui.tool_scroll_area.takeWidget()
  1809. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1810. self.ui.notebook.setTabText(2, "Tool")
  1811. if isinstance(edited_obj, GeometryObject):
  1812. obj_type = "Geometry"
  1813. self.geo_editor.update_fcgeometry(edited_obj)
  1814. # self.geo_editor.update_options(edited_obj)
  1815. # restore GUI to the Selected TAB
  1816. # Remove anything else in the AppGUI
  1817. self.ui.tool_scroll_area.takeWidget()
  1818. # update the geo object options so it is including the bounding box values
  1819. try:
  1820. xmin, ymin, xmax, ymax = edited_obj.bounds(flatten=True)
  1821. edited_obj.options['xmin'] = xmin
  1822. edited_obj.options['ymin'] = ymin
  1823. edited_obj.options['xmax'] = xmax
  1824. edited_obj.options['ymax'] = ymax
  1825. except AttributeError as e:
  1826. self.inform.emit('[WARNING] %s' % _("Object empty after edit."))
  1827. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  1828. edited_obj.build_ui()
  1829. edited_obj.plot()
  1830. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1831. elif isinstance(edited_obj, GerberObject):
  1832. obj_type = "Gerber"
  1833. self.grb_editor.update_fcgerber()
  1834. # self.grb_editor.update_options(edited_obj)
  1835. # delete the old object (the source object) if it was an empty one
  1836. try:
  1837. if len(edited_obj.solid_geometry) == 0:
  1838. old_name = edited_obj.options['name']
  1839. self.collection.delete_by_name(old_name)
  1840. except TypeError:
  1841. # if the solid_geometry is a single Polygon the len() will not work
  1842. # in any case, falling here means that we have something in the solid_geometry, even if only
  1843. # a single Polygon, therefore we pass this
  1844. pass
  1845. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1846. # restore GUI to the Selected TAB
  1847. # Remove anything else in the AppGUI
  1848. self.ui.selected_scroll_area.takeWidget()
  1849. elif isinstance(edited_obj, ExcellonObject):
  1850. obj_type = "Excellon"
  1851. self.exc_editor.update_fcexcellon(edited_obj)
  1852. # self.exc_editor.update_options(edited_obj)
  1853. # restore GUI to the Selected TAB
  1854. # Remove anything else in the AppGUI
  1855. self.ui.tool_scroll_area.takeWidget()
  1856. # delete the old object (the source object) if it was an empty one
  1857. if len(edited_obj.drills) == 0 and len(edited_obj.slots) == 0:
  1858. old_name = edited_obj.options['name']
  1859. self.collection.delete_by_name(name=old_name)
  1860. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1861. else:
  1862. self.inform.emit('[WARNING_NOTCL] %s' %
  1863. _("Select a Gerber, Geometry or Excellon Object to update."))
  1864. return
  1865. self.inform.emit('[selected] %s %s' % (obj_type, _("is updated, returning to App...")))
  1866. elif response == bt_no:
  1867. # clean the Tools Tab
  1868. self.ui.tool_scroll_area.takeWidget()
  1869. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1870. self.ui.notebook.setTabText(2, "Tool")
  1871. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor exited. Editor content was not saved."))
  1872. if isinstance(edited_obj, GeometryObject):
  1873. self.geo_editor.deactivate()
  1874. edited_obj.build_ui()
  1875. edited_obj.plot()
  1876. elif isinstance(edited_obj, GerberObject):
  1877. self.grb_editor.deactivate_grb_editor()
  1878. edited_obj.build_ui()
  1879. elif isinstance(edited_obj, ExcellonObject):
  1880. self.exc_editor.deactivate()
  1881. edited_obj.build_ui()
  1882. else:
  1883. self.inform.emit('[WARNING_NOTCL] %s' %
  1884. _("Select a Gerber, Geometry or Excellon Object to update."))
  1885. return
  1886. elif response == bt_cancel:
  1887. return
  1888. # edited_obj.set_ui(edited_obj.ui_type(decimals=self.decimals))
  1889. # edited_obj.build_ui()
  1890. # Switch notebook to Selected page
  1891. # self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  1892. else:
  1893. if isinstance(edited_obj, GeometryObject):
  1894. self.geo_editor.deactivate()
  1895. elif isinstance(edited_obj, GerberObject):
  1896. self.grb_editor.deactivate_grb_editor()
  1897. elif isinstance(edited_obj, ExcellonObject):
  1898. self.exc_editor.deactivate()
  1899. else:
  1900. self.inform.emit('[WARNING_NOTCL] %s' %
  1901. _("Select a Gerber, Geometry or Excellon Object to update."))
  1902. return
  1903. # if notebook is hidden we show it
  1904. if self.ui.splitter.sizes()[0] == 0:
  1905. self.ui.splitter.setSizes([1, 1])
  1906. # restore the call_source to app
  1907. self.call_source = 'app'
  1908. # edited_obj.plot()
  1909. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  1910. self.ui.plot_tab_area.protectTab(0)
  1911. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  1912. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  1913. self.ui.project_frame.setDisabled(False)
  1914. def get_last_folder(self):
  1915. """
  1916. Get the folder path from where the last file was opened.
  1917. :return: String, last opened folder path
  1918. """
  1919. return self.defaults["global_last_folder"]
  1920. def get_last_save_folder(self):
  1921. """
  1922. Get the folder path from where the last file was saved.
  1923. :return: String, last saved folder path
  1924. """
  1925. loc = self.defaults["global_last_save_folder"]
  1926. if loc is None:
  1927. loc = self.defaults["global_last_folder"]
  1928. if loc is None:
  1929. loc = os.path.dirname(__file__)
  1930. return loc
  1931. @QtCore.pyqtSlot(str)
  1932. @QtCore.pyqtSlot(str, bool)
  1933. def info(self, msg, shell_echo=True):
  1934. """
  1935. Informs the user. Normally on the status bar, optionally
  1936. also on the shell.
  1937. :param msg: Text to write.
  1938. :type msg: str
  1939. :param shell_echo: Control if to display the message msg in the Shell
  1940. :type shell_echo: bool
  1941. :return: None
  1942. """
  1943. # Type of message in brackets at the beginning of the message.
  1944. match = re.search(r"\[(.*)\](.*)", msg)
  1945. if match:
  1946. level = match.group(1)
  1947. msg_ = match.group(2)
  1948. self.ui.fcinfo.set_status(str(msg_), level=level)
  1949. if shell_echo is True:
  1950. if level.lower() == "error":
  1951. self.shell_message(msg, error=True, show=True)
  1952. elif level.lower() == "warning":
  1953. self.shell_message(msg, warning=True, show=True)
  1954. elif level.lower() == "error_notcl":
  1955. self.shell_message(msg, error=True, show=False)
  1956. elif level.lower() == "warning_notcl":
  1957. self.shell_message(msg, warning=True, show=False)
  1958. elif level.lower() == "success":
  1959. self.shell_message(msg, success=True, show=False)
  1960. elif level.lower() == "selected":
  1961. self.shell_message(msg, selected=True, show=False)
  1962. else:
  1963. self.shell_message(msg, show=False)
  1964. else:
  1965. self.ui.fcinfo.set_status(str(msg), level="info")
  1966. # make sure that if the message is to clear the infobar with a space
  1967. # is not printed over and over on the shell
  1968. if msg != '' and shell_echo is True:
  1969. self.shell_message(msg)
  1970. def on_import_preferences(self):
  1971. """
  1972. Loads the application default settings from a saved file into
  1973. ``self.defaults`` dictionary.
  1974. :return: None
  1975. """
  1976. self.defaults.report_usage("on_import_preferences")
  1977. App.log.debug("App.on_import_preferences()")
  1978. # Show file chooser
  1979. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  1980. try:
  1981. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  1982. directory=self.data_path,
  1983. filter=filter_)
  1984. except TypeError:
  1985. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  1986. filter=filter_)
  1987. filename = str(filename)
  1988. if filename == "":
  1989. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  1990. return
  1991. # Load in the defaults from the chosen file
  1992. self.defaults.load(filename=filename)
  1993. self.preferencesUiManager.on_preferences_edited()
  1994. self.inform.emit('[success] %s: %s' % (_("Imported Defaults from"), filename))
  1995. def on_export_preferences(self):
  1996. """
  1997. Save the defaults dictionary to a file.
  1998. :return: None
  1999. """
  2000. self.defaults.report_usage("on_export_preferences")
  2001. App.log.debug("on_export_preferences()")
  2002. # defaults_file_content = None
  2003. # Show file chooser
  2004. date = str(datetime.today()).rpartition('.')[0]
  2005. date = ''.join(c for c in date if c not in ':-')
  2006. date = date.replace(' ', '_')
  2007. filter__ = "Config File .FlatConfig (*.FlatConfig);;All Files (*.*)"
  2008. try:
  2009. filename, _f = FCFileSaveDialog.get_saved_filename(
  2010. caption=_("Export FlatCAM Preferences"),
  2011. directory=self.data_path + '/preferences_' + date,
  2012. ext_filter=filter__
  2013. )
  2014. except TypeError:
  2015. filename, _f = FCFileSaveDialog.get_saved_filename(
  2016. caption=_("Export FlatCAM Preferences"), ext_filter=filter__)
  2017. filename = str(filename)
  2018. if filename == "":
  2019. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2020. return
  2021. # Update options
  2022. self.preferencesUiManager.defaults_read_form()
  2023. self.defaults.propagate_defaults()
  2024. # Save update options
  2025. try:
  2026. self.defaults.write(filename=filename)
  2027. except Exception:
  2028. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2029. return
  2030. if self.defaults["global_open_style"] is False:
  2031. self.file_opened.emit("preferences", filename)
  2032. self.file_saved.emit("preferences", filename)
  2033. self.inform.emit('[success] %s: %s' % (_("Exported preferences to"), filename))
  2034. def save_to_file(self, content_to_save, txt_content):
  2035. """
  2036. Save something to a file.
  2037. :return: None
  2038. """
  2039. self.defaults.report_usage("save_to_file")
  2040. App.log.debug("save_to_file()")
  2041. self.date = str(datetime.today()).rpartition('.')[0]
  2042. self.date = ''.join(c for c in self.date if c not in ':-')
  2043. self.date = self.date.replace(' ', '_')
  2044. filter__ = "HTML File .html (*.html);;TXT File .txt (*.txt);;All Files (*.*)"
  2045. path_to_save = self.defaults["global_last_save_folder"] if \
  2046. self.defaults["global_last_save_folder"] is not None else self.data_path
  2047. try:
  2048. filename, _f = FCFileSaveDialog.get_saved_filename(
  2049. caption=_("Save to file"),
  2050. directory=path_to_save + '/file_' + self.date,
  2051. ext_filter=filter__
  2052. )
  2053. except TypeError:
  2054. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save to file"), ext_filter=filter__)
  2055. filename = str(filename)
  2056. if filename == "":
  2057. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2058. return
  2059. else:
  2060. try:
  2061. with open(filename, 'w') as f:
  2062. ___ = f.read()
  2063. except PermissionError:
  2064. self.inform.emit('[WARNING] %s' %
  2065. _("Permission denied, saving not possible.\n"
  2066. "Most likely another app is holding the file open and not accessible."))
  2067. return
  2068. except IOError:
  2069. App.log.debug('Creating a new file ...')
  2070. f = open(filename, 'w')
  2071. f.close()
  2072. except Exception:
  2073. e = sys.exc_info()[0]
  2074. App.log.error("Could not load the file.")
  2075. App.log.error(str(e))
  2076. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load the file."))
  2077. return
  2078. # Save content
  2079. if filename.rpartition('.')[2].lower() == 'html':
  2080. file_content = content_to_save
  2081. else:
  2082. file_content = txt_content
  2083. try:
  2084. with open(filename, "w") as f:
  2085. f.write(file_content)
  2086. except Exception:
  2087. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2088. return
  2089. self.inform.emit('[success] %s: %s' % (_("Exported file to"), filename))
  2090. def register_recent(self, kind, filename):
  2091. """
  2092. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  2093. dictionary.
  2094. :param kind: type of file that was opened
  2095. :param filename: the path and file name for the file that was opened
  2096. :return:
  2097. """
  2098. self.log.debug("register_recent()")
  2099. self.log.debug(" %s" % kind)
  2100. self.log.debug(" %s" % filename)
  2101. record = {'kind': str(kind), 'filename': str(filename)}
  2102. if record in self.recent:
  2103. return
  2104. if record in self.recent_projects:
  2105. return
  2106. if record['kind'] == 'project':
  2107. self.recent_projects.insert(0, record)
  2108. else:
  2109. self.recent.insert(0, record)
  2110. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  2111. self.recent.pop()
  2112. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  2113. self.recent_projects.pop()
  2114. try:
  2115. f = open(self.data_path + '/recent.json', 'w')
  2116. except IOError:
  2117. App.log.error("Failed to open recent items file for writing.")
  2118. self.inform.emit('[ERROR_NOTCL] %s' %
  2119. _('Failed to open recent files file for writing.'))
  2120. return
  2121. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  2122. f.close()
  2123. try:
  2124. fp = open(self.data_path + '/recent_projects.json', 'w')
  2125. except IOError:
  2126. App.log.error("Failed to open recent items file for writing.")
  2127. self.inform.emit('[ERROR_NOTCL] %s' %
  2128. _('Failed to open recent projects file for writing.'))
  2129. return
  2130. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  2131. fp.close()
  2132. # Re-build the recent items menu
  2133. self.setup_recent_items()
  2134. def on_about(self):
  2135. """
  2136. Displays the "about" dialog found in the Menu --> Help.
  2137. :return: None
  2138. """
  2139. self.defaults.report_usage("on_about")
  2140. version = self.version
  2141. version_date = self.version_date
  2142. beta = self.beta
  2143. class AboutDialog(QtWidgets.QDialog):
  2144. def __init__(self, app, parent=None):
  2145. QtWidgets.QDialog.__init__(self, parent)
  2146. self.app = app
  2147. # Icon and title
  2148. self.setWindowIcon(parent.app_icon)
  2149. self.setWindowTitle(_("About FlatCAM"))
  2150. self.resize(600, 200)
  2151. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  2152. # self.setStyleSheet(
  2153. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  2154. # "background-attachment: fixed"
  2155. # )
  2156. # bgimage = QtGui.QImage(self.resource_location + '/flatcam_icon256.png')
  2157. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  2158. # palette = QtGui.QPalette()
  2159. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  2160. # self.setPalette(palette)
  2161. logo = QtWidgets.QLabel()
  2162. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/flatcam_icon256.png'))
  2163. title = QtWidgets.QLabel(
  2164. "<font size=8><B>FlatCAM</B></font><BR>"
  2165. "{title}<BR>"
  2166. "<BR>"
  2167. "<BR>"
  2168. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  2169. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  2170. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">"
  2171. "<B>{issue}</B></a><BR>".format(
  2172. title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  2173. devel=_("Development"),
  2174. down=_("DOWNLOAD"),
  2175. issue=_("Issue tracker"))
  2176. )
  2177. title.setOpenExternalLinks(True)
  2178. closebtn = QtWidgets.QPushButton(_("Close"))
  2179. tab_widget = QtWidgets.QTabWidget()
  2180. description_label = QtWidgets.QLabel(
  2181. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  2182. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  2183. version=version,
  2184. beta=('BETA' if beta else ''),
  2185. date=version_date,
  2186. arch=platform.architecture()[0])
  2187. )
  2188. description_label.setOpenExternalLinks(True)
  2189. lic_lbl_header = QtWidgets.QLabel(
  2190. '%s:<br>%s<br>' % (
  2191. _('Licensed under the MIT license'),
  2192. "<a href = \"http://www.opensource.org/licenses/mit-license.php\">"
  2193. "http://www.opensource.org/licenses/mit-license.php</a>"
  2194. )
  2195. )
  2196. lic_lbl_header.setOpenExternalLinks(True)
  2197. lic_lbl_body = QtWidgets.QLabel(
  2198. _(
  2199. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  2200. 'of this software and associated documentation files (the "Software"), to deal\n'
  2201. 'in the Software without restriction, including without limitation the rights\n'
  2202. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  2203. 'copies of the Software, and to permit persons to whom the Software is\n'
  2204. 'furnished to do so, subject to the following conditions:\n\n'
  2205. 'The above copyright notice and this permission notice shall be included in\n'
  2206. 'all copies or substantial portions of the Software.\n\n'
  2207. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  2208. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  2209. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  2210. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  2211. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  2212. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  2213. 'THE SOFTWARE.'
  2214. )
  2215. )
  2216. attributions_label = QtWidgets.QLabel(
  2217. _(
  2218. 'Some of the icons used are from the following sources:<br>'
  2219. '<div>Icons by <a href="https://www.flaticon.com/authors/freepik" '
  2220. 'title="Freepik">Freepik</a> from <a href="https://www.flaticon.com/" '
  2221. 'title="Flaticon">www.flaticon.com</a></div>'
  2222. '<div>Icons by <a target="_blank" href="https://icons8.com">Icons8</a></div>'
  2223. 'Icons by <a href="http://www.onlinewebfonts.com">oNline Web Fonts</a>'
  2224. )
  2225. )
  2226. attributions_label.setOpenExternalLinks(True)
  2227. # layouts
  2228. layout1 = QtWidgets.QVBoxLayout()
  2229. layout1_1 = QtWidgets.QHBoxLayout()
  2230. layout1_2 = QtWidgets.QHBoxLayout()
  2231. layout2 = QtWidgets.QHBoxLayout()
  2232. layout3 = QtWidgets.QHBoxLayout()
  2233. self.setLayout(layout1)
  2234. layout1.addLayout(layout1_1)
  2235. layout1.addLayout(layout1_2)
  2236. layout1.addLayout(layout2)
  2237. layout1.addLayout(layout3)
  2238. layout1_1.addStretch()
  2239. layout1_1.addWidget(description_label)
  2240. layout1_2.addWidget(tab_widget)
  2241. self.splash_tab = QtWidgets.QWidget()
  2242. self.splash_tab.setObjectName("splash_about")
  2243. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  2244. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  2245. tab_widget.addTab(self.splash_tab, _("Splash"))
  2246. self.programmmers_tab = QtWidgets.QWidget()
  2247. self.programmmers_tab.setObjectName("programmers_about")
  2248. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  2249. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  2250. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  2251. self.translators_tab = QtWidgets.QWidget()
  2252. self.translators_tab.setObjectName("translators_about")
  2253. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  2254. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  2255. tab_widget.addTab(self.translators_tab, _("Translators"))
  2256. self.license_tab = QtWidgets.QWidget()
  2257. self.license_tab.setObjectName("license_about")
  2258. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  2259. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  2260. tab_widget.addTab(self.license_tab, _("License"))
  2261. self.attributions_tab = QtWidgets.QWidget()
  2262. self.attributions_tab.setObjectName("attributions_about")
  2263. self.attributions_tab_layout = QtWidgets.QVBoxLayout(self.attributions_tab)
  2264. self.attributions_tab_layout.setContentsMargins(2, 2, 2, 2)
  2265. tab_widget.addTab(self.attributions_tab, _("Attributions"))
  2266. self.splash_tab_layout.addWidget(logo, stretch=0)
  2267. self.splash_tab_layout.addWidget(title, stretch=1)
  2268. pal = QtGui.QPalette()
  2269. pal.setColor(QtGui.QPalette.Background, Qt.white)
  2270. self.prog_grid_lay = QtWidgets.QGridLayout()
  2271. self.prog_grid_lay.setHorizontalSpacing(20)
  2272. self.prog_grid_lay.setColumnStretch(0, 0)
  2273. self.prog_grid_lay.setColumnStretch(2, 1)
  2274. prog_widget = QtWidgets.QWidget()
  2275. prog_widget.setLayout(self.prog_grid_lay)
  2276. prog_scroll = QtWidgets.QScrollArea()
  2277. prog_scroll.setWidget(prog_widget)
  2278. prog_scroll.setWidgetResizable(True)
  2279. prog_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2280. prog_scroll.setPalette(pal)
  2281. self.programmmers_tab_layout.addWidget(prog_scroll)
  2282. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")), 0, 0)
  2283. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Status")), 0, 1)
  2284. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  2285. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Juan Pablo Caram"), 1, 0)
  2286. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("Program Author")), 1, 1)
  2287. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<>"), 1, 2)
  2288. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Denis Hayrullin"), 2, 0)
  2289. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Kamil Sopko"), 3, 0)
  2290. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 0)
  2291. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("BETA Maintainer >= 2019")), 4, 1)
  2292. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 2)
  2293. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 5, 0)
  2294. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "David Robertson"), 6, 0)
  2295. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Matthieu Berthomé"), 7, 0)
  2296. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Evans"), 8, 0)
  2297. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Victor Benso"), 9, 0)
  2298. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 10, 0)
  2299. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jørn Sandvik Nilsson"), 12, 0)
  2300. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lei Zheng"), 13, 0)
  2301. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Leandro Heck"), 14, 0)
  2302. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marco A Quezada"), 15, 0)
  2303. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 16, 0)
  2304. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Cedric Dussud"), 20, 0)
  2305. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Hemingway"), 22, 0)
  2306. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Damian Wrobel"), 24, 0)
  2307. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Daniel Sallin"), 28, 0)
  2308. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 32, 0)
  2309. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Bruno Vunderl"), 40, 0)
  2310. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Gonzalo Lopez"), 42, 0)
  2311. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jakob Staudt"), 45, 0)
  2312. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Smith"), 49, 0)
  2313. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 52, 0)
  2314. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Barnaby Walters"), 55, 0)
  2315. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Steve Martina"), 57, 0)
  2316. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Thomas Duffin"), 59, 0)
  2317. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 61, 0)
  2318. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 63, 0)
  2319. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Alex Lazar"), 64, 0)
  2320. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Breneman"), 65, 0)
  2321. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Eric Varsanyi"), 67, 0)
  2322. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lubos Medovarsky"), 69, 0)
  2323. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 74, 0)
  2324. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Idechix"), 100, 0)
  2325. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@SM"), 101, 0)
  2326. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@grbf"), 102, 0)
  2327. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Symonty"), 103, 0)
  2328. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@mgix"), 104, 0)
  2329. self.translator_grid_lay = QtWidgets.QGridLayout()
  2330. self.translator_grid_lay.setColumnStretch(0, 0)
  2331. self.translator_grid_lay.setColumnStretch(1, 0)
  2332. self.translator_grid_lay.setColumnStretch(2, 1)
  2333. self.translator_grid_lay.setColumnStretch(3, 0)
  2334. # trans_widget = QtWidgets.QWidget()
  2335. # trans_widget.setLayout(self.translator_grid_lay)
  2336. # self.translators_tab_layout.addWidget(trans_widget)
  2337. # self.translators_tab_layout.addStretch()
  2338. trans_widget = QtWidgets.QWidget()
  2339. trans_widget.setLayout(self.translator_grid_lay)
  2340. trans_scroll = QtWidgets.QScrollArea()
  2341. trans_scroll.setWidget(trans_widget)
  2342. trans_scroll.setWidgetResizable(True)
  2343. trans_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2344. trans_scroll.setPalette(pal)
  2345. self.translators_tab_layout.addWidget(trans_scroll)
  2346. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  2347. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  2348. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Corrections")), 0, 2)
  2349. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 3)
  2350. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "BR - Portuguese"), 1, 0)
  2351. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  2352. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<carlos.stein@gmail.com>"), 1, 3)
  2353. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "French"), 2, 0)
  2354. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 2, 1)
  2355. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 2, 2)
  2356. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 2, 3)
  2357. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Hungarian"), 3, 0)
  2358. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 1)
  2359. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 2)
  2360. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 3)
  2361. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Italian"), 4, 0)
  2362. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Golfetto Massimiliano"), 4, 1)
  2363. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 4, 2)
  2364. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<golfetto.pcb@gmail.com>"), 4, 3)
  2365. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 5, 0)
  2366. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 5, 1)
  2367. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jens Karstedt, Detlef Eckardt"), 5, 2)
  2368. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 5, 3)
  2369. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 6, 0)
  2370. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 6, 1)
  2371. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 6, 3)
  2372. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 7, 0)
  2373. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 7, 1)
  2374. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 7, 3)
  2375. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 8, 0)
  2376. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 8, 1)
  2377. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 8, 2)
  2378. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 8, 3)
  2379. self.translator_grid_lay.setColumnStretch(0, 0)
  2380. self.translators_tab_layout.addStretch()
  2381. self.license_tab_layout.addWidget(lic_lbl_header)
  2382. self.license_tab_layout.addWidget(lic_lbl_body)
  2383. self.license_tab_layout.addStretch()
  2384. self.attributions_tab_layout.addWidget(attributions_label)
  2385. self.attributions_tab_layout.addStretch()
  2386. layout3.addStretch()
  2387. layout3.addWidget(closebtn)
  2388. closebtn.clicked.connect(self.accept)
  2389. AboutDialog(app=self, parent=self.ui).exec_()
  2390. def on_readme(self):
  2391. class AboutDialog(QtWidgets.QDialog):
  2392. def __init__(self, app, parent=None):
  2393. QtWidgets.QDialog.__init__(self, parent)
  2394. self.app = app
  2395. open_source_link = "<a href = 'https://opensource.org/'<b>Open Source</b></a>"
  2396. new_features_link = "<a href = 'https://bitbucket.org/jpcgt/flatcam/pull-requests/'" \
  2397. "<b>new features</b></a>"
  2398. bugs_link = "<a href = 'https://bitbucket.org/jpcgt/flatcam/issues/new'<b>report bugs</b></a>"
  2399. donation_link = "<a href = 'https://www.paypal.com/cgi-bin/webscr?cmd=_" \
  2400. "donations&business=WLTJJ3Q77D98L&currency_code=USD&source=url'<b>donation</b></a>"
  2401. # Icon and title
  2402. self.setWindowIcon(parent.app_icon)
  2403. self.setWindowTitle(_("Important Information's"))
  2404. self.resize(720, 330)
  2405. logo = QtWidgets.QLabel()
  2406. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/contribute256.png'))
  2407. content = QtWidgets.QLabel(
  2408. "This program is %s and free in a very wide meaning of the word.<br>"
  2409. "Yet it cannot evolve without <b>contributions</b>.<br><br>"
  2410. "If you want to see this application evolve and grow, or if you make money with it,<br>"
  2411. "you can <b>contribute</b> to the development yourself by:<br>"
  2412. "<ul>"
  2413. "<li>adding %s through a Pull Request on the Bitbucket repository</li>"
  2414. "<li>%s by providing the steps required to reproduce the bug</li>"
  2415. "<li>or by making a %s.</li>"
  2416. "</ul>"
  2417. "There are no strings attached.<br>"
  2418. "You don't have to make a %s, and it is totally optional but:"
  2419. "<ul>"
  2420. "<li>it will be welcomed with joy &#128077;</li>"
  2421. "<li>it will give me a reason to continue &#128513;</li>"
  2422. "</ul>" %
  2423. (open_source_link, new_features_link, bugs_link, donation_link, donation_link)
  2424. )
  2425. content.setOpenExternalLinks(True)
  2426. closebtn = QtWidgets.QPushButton(_("Close"))
  2427. # layouts
  2428. layout1 = QtWidgets.QVBoxLayout()
  2429. self.setLayout(layout1)
  2430. pal = QtGui.QPalette()
  2431. pal.setColor(QtGui.QPalette.Background, Qt.white)
  2432. self.grid_lay = QtWidgets.QGridLayout()
  2433. self.grid_lay.setHorizontalSpacing(20)
  2434. self.grid_lay.setColumnStretch(0, 0)
  2435. self.grid_lay.setColumnStretch(1, 1)
  2436. content_widget = QtWidgets.QWidget()
  2437. content_widget.setLayout(self.grid_lay)
  2438. scroll_area = QtWidgets.QScrollArea()
  2439. scroll_area.setWidget(content_widget)
  2440. scroll_area.setWidgetResizable(True)
  2441. scroll_area.setFrameShape(QtWidgets.QFrame.NoFrame)
  2442. scroll_area.setPalette(pal)
  2443. self.grid_lay.addWidget(logo, 0, 0)
  2444. self.grid_lay.addWidget(content, 0, 1)
  2445. layout1.addWidget(scroll_area)
  2446. layout2 = QtWidgets.QHBoxLayout()
  2447. layout1.addLayout(layout2)
  2448. layout2.addStretch()
  2449. layout2.addWidget(closebtn)
  2450. closebtn.clicked.connect(self.accept)
  2451. AboutDialog(app=self, parent=self.ui).exec_()
  2452. def install_bookmarks(self, book_dict=None):
  2453. """
  2454. Install the bookmarks actions in the Help menu -> Bookmarks
  2455. :param book_dict: a dict having the actions text as keys and the weblinks as the values
  2456. :return: None
  2457. """
  2458. if book_dict is None:
  2459. self.defaults["global_bookmarks"].update(
  2460. {
  2461. '1': ['FlatCAM', "http://flatcam.org"],
  2462. '2': ['Backup Site', ""]
  2463. }
  2464. )
  2465. else:
  2466. self.defaults["global_bookmarks"].clear()
  2467. self.defaults["global_bookmarks"].update(book_dict)
  2468. # first try to disconnect if somehow they get connected from elsewhere
  2469. for act in self.ui.menuhelp_bookmarks.actions():
  2470. try:
  2471. act.triggered.disconnect()
  2472. except TypeError:
  2473. pass
  2474. # clear all actions except the last one who is the Bookmark manager
  2475. if act is self.ui.menuhelp_bookmarks.actions()[-1]:
  2476. pass
  2477. else:
  2478. self.ui.menuhelp_bookmarks.removeAction(act)
  2479. bm_limit = int(self.defaults["global_bookmarks_limit"])
  2480. if self.defaults["global_bookmarks"]:
  2481. # order the self.defaults["global_bookmarks"] dict keys by the value as integer
  2482. # the whole convoluted things is because when serializing the self.defaults (on app close or save)
  2483. # the JSON is first making the keys as strings (therefore I have to use strings too
  2484. # or do the conversion :(
  2485. # )
  2486. # and it is ordering them (actually I want that to make the defaults easy to search within) but making
  2487. # the '10' entry jsut after '1' therefore ordering as strings
  2488. sorted_bookmarks = sorted(list(self.defaults["global_bookmarks"].items())[:bm_limit],
  2489. key=lambda x: int(x[0]))
  2490. for entry, bookmark in sorted_bookmarks:
  2491. title = bookmark[0]
  2492. weblink = bookmark[1]
  2493. act = QtWidgets.QAction(parent=self.ui.menuhelp_bookmarks)
  2494. act.setText(title)
  2495. act.setIcon(QtGui.QIcon(self.resource_location + '/link16.png'))
  2496. # from here: https://stackoverflow.com/questions/20390323/pyqt-dynamic-generate-qmenu-action-and-connect
  2497. if title == 'Backup Site' and weblink == "":
  2498. act.triggered.connect(self.on_backup_site)
  2499. else:
  2500. act.triggered.connect(lambda sig, link=weblink: webbrowser.open(link))
  2501. self.ui.menuhelp_bookmarks.insertAction(self.ui.menuhelp_bookmarks_manager, act)
  2502. self.ui.menuhelp_bookmarks_manager.triggered.connect(self.on_bookmarks_manager)
  2503. def on_bookmarks_manager(self):
  2504. """
  2505. Adds the bookmark manager in a Tab in Plot Area
  2506. :return:
  2507. """
  2508. for idx in range(self.ui.plot_tab_area.count()):
  2509. if self.ui.plot_tab_area.tabText(idx) == _("Bookmarks Manager"):
  2510. # there can be only one instance of Bookmark Manager at one time
  2511. return
  2512. # BookDialog(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui).exec_()
  2513. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui)
  2514. self.book_dialog_tab.setObjectName("bookmarks_tab")
  2515. # add the tab if it was closed
  2516. self.ui.plot_tab_area.addTab(self.book_dialog_tab, _("Bookmarks Manager"))
  2517. # delete the absolute and relative position and messages in the infobar
  2518. self.ui.position_label.setText("")
  2519. # self.ui.rel_position_label.setText("")
  2520. # Switch plot_area to preferences page
  2521. self.ui.plot_tab_area.setCurrentWidget(self.book_dialog_tab)
  2522. def on_backup_site(self):
  2523. msgbox = QtWidgets.QMessageBox()
  2524. msgbox.setText(_("This entry will resolve to another website if:\n\n"
  2525. "1. FlatCAM.org website is down\n"
  2526. "2. Someone forked FlatCAM project and wants to point\n"
  2527. "to his own website\n\n"
  2528. "If you can't get any informations about FlatCAM beta\n"
  2529. "use the YouTube channel link from the Help menu."))
  2530. msgbox.setWindowTitle(_("Alternative website"))
  2531. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/globe16.png'))
  2532. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  2533. bt_yes = msgbox.addButton(_('Close'), QtWidgets.QMessageBox.YesRole)
  2534. msgbox.setDefaultButton(bt_yes)
  2535. msgbox.exec_()
  2536. # response = msgbox.clickedButton()
  2537. def on_file_savedefaults(self):
  2538. """
  2539. Callback for menu item File->Save Defaults. Saves application default options
  2540. ``self.defaults`` to current_defaults.FlatConfig.
  2541. :return: None
  2542. """
  2543. self.preferencesUiManager.save_defaults()
  2544. def final_save(self):
  2545. """
  2546. Callback for doing a preferences save to file whenever the application is about to quit.
  2547. If the project has changes, it will ask the user to save the project.
  2548. :return: None
  2549. """
  2550. if self.save_in_progress:
  2551. self.inform.emit('[WARNING_NOTCL] %s' % _("Application is saving the project. Please wait ..."))
  2552. return
  2553. if self.should_we_save and self.collection.get_list():
  2554. msgbox = QtWidgets.QMessageBox()
  2555. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  2556. "\n"
  2557. "Do you want to Save the project?"))
  2558. msgbox.setWindowTitle(_("Save changes"))
  2559. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  2560. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  2561. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2562. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2563. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2564. msgbox.setDefaultButton(bt_yes)
  2565. msgbox.exec_()
  2566. response = msgbox.clickedButton()
  2567. if response == bt_yes:
  2568. try:
  2569. self.trayIcon.hide()
  2570. except Exception:
  2571. pass
  2572. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  2573. elif response == bt_no:
  2574. try:
  2575. self.trayIcon.hide()
  2576. except Exception:
  2577. pass
  2578. self.quit_application()
  2579. elif response == bt_cancel:
  2580. return
  2581. else:
  2582. try:
  2583. self.trayIcon.hide()
  2584. except Exception:
  2585. pass
  2586. self.quit_application()
  2587. def quit_application(self):
  2588. """
  2589. Called (as a pyslot or not) when the application is quit.
  2590. :return: None
  2591. """
  2592. self.preferencesUiManager.save_defaults(silent=True)
  2593. log.debug("App.quit_application() --> App Defaults saved.")
  2594. if self.cmd_line_headless != 1:
  2595. # save app state to file
  2596. stgs = QSettings("Open Source", "FlatCAM")
  2597. stgs.setValue('saved_gui_state', self.ui.saveState())
  2598. stgs.setValue('maximized_gui', self.ui.isMaximized())
  2599. stgs.setValue(
  2600. 'language',
  2601. self.ui.general_defaults_form.general_app_group.language_cb.get_value()
  2602. )
  2603. stgs.setValue(
  2604. 'notebook_font_size',
  2605. self.ui.general_defaults_form.general_app_set_group.notebook_font_size_spinner.get_value()
  2606. )
  2607. stgs.setValue(
  2608. 'axis_font_size',
  2609. self.ui.general_defaults_form.general_app_set_group.axis_font_size_spinner.get_value()
  2610. )
  2611. stgs.setValue(
  2612. 'textbox_font_size',
  2613. self.ui.general_defaults_form.general_app_set_group.textbox_font_size_spinner.get_value()
  2614. )
  2615. stgs.setValue(
  2616. 'hud_font_size',
  2617. self.ui.general_defaults_form.general_app_set_group.hud_font_size_spinner.get_value()
  2618. )
  2619. stgs.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  2620. stgs.setValue(
  2621. 'machinist',
  2622. 1 if self.ui.general_defaults_form.general_app_set_group.machinist_cb.get_value() else 0
  2623. )
  2624. # This will write the setting to the platform specific storage.
  2625. del stgs
  2626. log.debug("App.quit_application() --> App UI state saved.")
  2627. # try to quit the Socket opened by ArgsThread class
  2628. try:
  2629. self.new_launch.stop.emit()
  2630. except Exception as err:
  2631. log.debug("App.quit_application() --> %s" % str(err))
  2632. # try to quit the QThread that run ArgsThread class
  2633. try:
  2634. self.th.quit()
  2635. except Exception as e:
  2636. log.debug("App.quit_application() --> %s" % str(e))
  2637. # terminate workers
  2638. self.workers.__del__()
  2639. # quit app by signalling for self.kill_app() method
  2640. # self.close_app_signal.emit()
  2641. QtWidgets.qApp.quit()
  2642. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2643. # we use the following command
  2644. minor_v = sys.version_info.minor
  2645. if minor_v < 8:
  2646. sys.exit(0)
  2647. else:
  2648. os._exit(0) # fix to work with Python 3.8
  2649. @staticmethod
  2650. def kill_app():
  2651. QtWidgets.qApp.quit()
  2652. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2653. # we use the following command
  2654. sys.exit(0)
  2655. def on_portable_checked(self, state):
  2656. """
  2657. Callback called when the checkbox in Preferences GUI is checked.
  2658. It will set the application as portable by creating the preferences and recent files in the
  2659. 'config' folder found in the FlatCAM installation folder.
  2660. :param state: boolean, the state of the checkbox when clicked/checked
  2661. :return:
  2662. """
  2663. line_no = 0
  2664. data = None
  2665. if sys.platform != 'win32':
  2666. # this won't work in Linux or MacOS
  2667. return
  2668. # test if the app was frozen and choose the path for the configuration file
  2669. if getattr(sys, "frozen", False) is True:
  2670. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  2671. else:
  2672. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  2673. config_file = current_data_path + '\\configuration.txt'
  2674. try:
  2675. with open(config_file, 'r') as f:
  2676. try:
  2677. data = f.readlines()
  2678. except Exception as e:
  2679. log.debug('App.__init__() -->%s' % str(e))
  2680. return
  2681. except FileNotFoundError:
  2682. pass
  2683. for line in data:
  2684. line = line.strip('\n')
  2685. param = str(line).rpartition('=')
  2686. if param[0] == 'portable':
  2687. break
  2688. line_no += 1
  2689. if state:
  2690. data[line_no] = 'portable=True\n'
  2691. # create the new defauults files
  2692. # create current_defaults.FlatConfig file if there is none
  2693. try:
  2694. f = open(current_data_path + '/current_defaults.FlatConfig')
  2695. f.close()
  2696. except IOError:
  2697. App.log.debug('Creating empty current_defaults.FlatConfig')
  2698. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  2699. json.dump({}, f)
  2700. f.close()
  2701. # create factory_defaults.FlatConfig file if there is none
  2702. try:
  2703. f = open(current_data_path + '/factory_defaults.FlatConfig')
  2704. f.close()
  2705. except IOError:
  2706. App.log.debug('Creating empty factory_defaults.FlatConfig')
  2707. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  2708. json.dump({}, f)
  2709. f.close()
  2710. try:
  2711. f = open(current_data_path + '/recent.json')
  2712. f.close()
  2713. except IOError:
  2714. App.log.debug('Creating empty recent.json')
  2715. f = open(current_data_path + '/recent.json', 'w')
  2716. json.dump([], f)
  2717. f.close()
  2718. try:
  2719. fp = open(current_data_path + '/recent_projects.json')
  2720. fp.close()
  2721. except IOError:
  2722. App.log.debug('Creating empty recent_projects.json')
  2723. fp = open(current_data_path + '/recent_projects.json', 'w')
  2724. json.dump([], fp)
  2725. fp.close()
  2726. # save the current defaults to the new defaults file
  2727. self.preferencesUiManager.save_defaults(silent=True, data_path=current_data_path)
  2728. else:
  2729. data[line_no] = 'portable=False\n'
  2730. with open(config_file, 'w') as f:
  2731. f.writelines(data)
  2732. def on_register_files(self, obj_type=None):
  2733. """
  2734. Called whenever there is a need to register file extensions with FlatCAM.
  2735. Works only in Windows and should be called only when FlatCAM is run in Windows.
  2736. :param obj_type: the type of object to be register for.
  2737. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  2738. :return: None
  2739. """
  2740. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  2741. new_reg_path = 'Software\\Classes\\'
  2742. # find if the current user is admin
  2743. try:
  2744. is_admin = os.getuid() == 0
  2745. except AttributeError:
  2746. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  2747. if is_admin is True:
  2748. root_path = winreg.HKEY_LOCAL_MACHINE
  2749. else:
  2750. root_path = winreg.HKEY_CURRENT_USER
  2751. # create the keys
  2752. def set_reg(name, root_pth, new_reg_path, value):
  2753. try:
  2754. winreg.CreateKey(root_pth, new_reg_path)
  2755. with winreg.OpenKey(root_pth, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  2756. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  2757. return True
  2758. except WindowsError:
  2759. return False
  2760. # delete key in registry
  2761. def delete_reg(root_pth, reg_path, key_to_del):
  2762. key_to_del_path = reg_path + key_to_del
  2763. try:
  2764. winreg.DeleteKey(root_pth, key_to_del_path)
  2765. return True
  2766. except WindowsError:
  2767. return False
  2768. if obj_type is None or obj_type == 'excellon':
  2769. exc_list = \
  2770. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  2771. exc_list = [x for x in exc_list if x != '']
  2772. # register all keys in the Preferences window
  2773. for ext in exc_list:
  2774. new_k = new_reg_path + '.%s' % ext
  2775. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  2776. # and unregister those that are no longer in the Preferences windows but are in the file
  2777. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  2778. if ext not in exc_list:
  2779. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  2780. # now write the updated extensions to the self.defaults
  2781. # new_ext = ''
  2782. # for ext in exc_list:
  2783. # new_ext = new_ext + ext + ', '
  2784. # self.defaults["fa_excellon"] = new_ext
  2785. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  2786. if obj_type is None or obj_type == 'gcode':
  2787. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  2788. gco_list = [x for x in gco_list if x != '']
  2789. # register all keys in the Preferences window
  2790. for ext in gco_list:
  2791. new_k = new_reg_path + '.%s' % ext
  2792. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  2793. # and unregister those that are no longer in the Preferences windows but are in the file
  2794. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  2795. if ext not in gco_list:
  2796. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  2797. # now write the updated extensions to the self.defaults
  2798. # new_ext = ''
  2799. # for ext in gco_list:
  2800. # new_ext = new_ext + ext + ', '
  2801. # self.defaults["fa_gcode"] = new_ext
  2802. self.inform.emit('[success] %s' %
  2803. _("Selected GCode file extensions registered with FlatCAM."))
  2804. if obj_type is None or obj_type == 'gerber':
  2805. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  2806. grb_list = [x for x in grb_list if x != '']
  2807. # register all keys in the Preferences window
  2808. for ext in grb_list:
  2809. new_k = new_reg_path + '.%s' % ext
  2810. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  2811. # and unregister those that are no longer in the Preferences windows but are in the file
  2812. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  2813. if ext not in grb_list:
  2814. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  2815. # now write the updated extensions to the self.defaults
  2816. # new_ext = ''
  2817. # for ext in grb_list:
  2818. # new_ext = new_ext + ext + ', '
  2819. # self.defaults["fa_gerber"] = new_ext
  2820. self.inform.emit('[success] %s' %
  2821. _("Selected Gerber file extensions registered with FlatCAM."))
  2822. def add_extension(self, ext_type):
  2823. """
  2824. Add a file extension to the list for a specific object
  2825. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  2826. :return:
  2827. """
  2828. if ext_type == 'excellon':
  2829. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  2830. if new_ext == '':
  2831. return
  2832. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  2833. if new_ext in old_val:
  2834. return
  2835. old_val.append(new_ext)
  2836. old_val.sort()
  2837. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  2838. if ext_type == 'gcode':
  2839. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  2840. if new_ext == '':
  2841. return
  2842. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  2843. if new_ext in old_val:
  2844. return
  2845. old_val.append(new_ext)
  2846. old_val.sort()
  2847. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  2848. if ext_type == 'gerber':
  2849. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  2850. if new_ext == '':
  2851. return
  2852. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  2853. if new_ext in old_val:
  2854. return
  2855. old_val.append(new_ext)
  2856. old_val.sort()
  2857. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  2858. if ext_type == 'keyword':
  2859. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  2860. if new_kw == '':
  2861. return
  2862. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  2863. if new_kw in old_val:
  2864. return
  2865. old_val.append(new_kw)
  2866. old_val.sort()
  2867. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  2868. # update the self.myKeywords so the model is updated
  2869. self.autocomplete_kw_list = \
  2870. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  2871. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  2872. self.shell._edit.set_model_data(self.myKeywords)
  2873. def del_extension(self, ext_type):
  2874. """
  2875. Remove a file extension from the list for a specific object
  2876. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  2877. :return:
  2878. """
  2879. if ext_type == 'excellon':
  2880. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  2881. if new_ext == '':
  2882. return
  2883. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  2884. if new_ext not in old_val:
  2885. return
  2886. old_val.remove(new_ext)
  2887. old_val.sort()
  2888. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  2889. if ext_type == 'gcode':
  2890. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  2891. if new_ext == '':
  2892. return
  2893. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  2894. if new_ext not in old_val:
  2895. return
  2896. old_val.remove(new_ext)
  2897. old_val.sort()
  2898. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  2899. if ext_type == 'gerber':
  2900. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  2901. if new_ext == '':
  2902. return
  2903. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  2904. if new_ext not in old_val:
  2905. return
  2906. old_val.remove(new_ext)
  2907. old_val.sort()
  2908. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  2909. if ext_type == 'keyword':
  2910. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  2911. if new_kw == '':
  2912. return
  2913. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  2914. if new_kw not in old_val:
  2915. return
  2916. old_val.remove(new_kw)
  2917. old_val.sort()
  2918. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  2919. # update the self.myKeywords so the model is updated
  2920. self.autocomplete_kw_list = \
  2921. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  2922. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  2923. self.shell._edit.set_model_data(self.myKeywords)
  2924. def restore_extensions(self, ext_type):
  2925. """
  2926. Restore all file extensions associations with FlatCAM, for a specific object
  2927. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  2928. :return:
  2929. """
  2930. if ext_type == 'excellon':
  2931. # don't add 'txt' to the associations (too many files are .txt and not Excellon) but keep it in the list
  2932. # for the ability to open Excellon files with .txt extension
  2933. new_exc_list = deepcopy(self.exc_list)
  2934. try:
  2935. new_exc_list.remove('txt')
  2936. except ValueError:
  2937. pass
  2938. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(new_exc_list))
  2939. if ext_type == 'gcode':
  2940. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(self.gcode_list))
  2941. if ext_type == 'gerber':
  2942. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(self.grb_list))
  2943. if ext_type == 'keyword':
  2944. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(self.default_keywords))
  2945. # update the self.myKeywords so the model is updated
  2946. self.autocomplete_kw_list = self.default_keywords
  2947. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  2948. self.shell._edit.set_model_data(self.myKeywords)
  2949. def delete_all_extensions(self, ext_type):
  2950. """
  2951. Delete all file extensions associations with FlatCAM, for a specific object
  2952. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  2953. :return:
  2954. """
  2955. if ext_type == 'excellon':
  2956. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value('')
  2957. if ext_type == 'gcode':
  2958. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value('')
  2959. if ext_type == 'gerber':
  2960. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value('')
  2961. if ext_type == 'keyword':
  2962. self.ui.util_defaults_form.kw_group.kw_list_text.set_value('')
  2963. # update the self.myKeywords so the model is updated
  2964. self.myKeywords = self.tcl_commands_list + self.tcl_keywords
  2965. self.shell._edit.set_model_data(self.myKeywords)
  2966. def on_edit_join(self, name=None):
  2967. """
  2968. Callback for Edit->Join. Joins the selected geometry objects into
  2969. a new one.
  2970. :return: None
  2971. """
  2972. self.defaults.report_usage("on_edit_join()")
  2973. obj_name_single = str(name) if name else "Combo_SingleGeo"
  2974. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  2975. geo_type_set = set()
  2976. objs = self.collection.get_selected()
  2977. if len(objs) < 2:
  2978. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  2979. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  2980. return 'fail'
  2981. for obj in objs:
  2982. geo_type_set.add(obj.multigeo)
  2983. # if len(geo_type_list) == 1 means that all list elements are the same
  2984. if len(geo_type_set) != 1:
  2985. self.inform.emit('[ERROR] %s' %
  2986. _("Failed join. The Geometry objects are of different types.\n"
  2987. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  2988. "convert from one to another and retry joining \n"
  2989. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  2990. "the result may not be what was expected. \n"
  2991. "Check the generated GCODE."))
  2992. return
  2993. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  2994. if True in geo_type_set:
  2995. def initialize(geo_obj, app):
  2996. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=True)
  2997. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  2998. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  2999. for v in geo_obj.tools.values():
  3000. v['data']['name'] = obj_name_multi
  3001. self.app_obj.new_object("geometry", obj_name_multi, initialize)
  3002. else:
  3003. def initialize(geo_obj, app):
  3004. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=False)
  3005. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  3006. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3007. for v in geo_obj.tools.values():
  3008. v['data']['name'] = obj_name_single
  3009. self.app_obj.new_object("geometry", obj_name_single, initialize)
  3010. self.should_we_save = True
  3011. def on_edit_join_exc(self):
  3012. """
  3013. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  3014. a new Excellon.
  3015. :return: None
  3016. """
  3017. self.defaults.report_usage("on_edit_join_exc()")
  3018. objs = self.collection.get_selected()
  3019. for obj in objs:
  3020. if not isinstance(obj, ExcellonObject):
  3021. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Excellon joining works only on Excellon objects."))
  3022. return
  3023. if len(objs) < 2:
  3024. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3025. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3026. return 'fail'
  3027. def initialize(exc_obj, app):
  3028. ExcellonObject.merge(exc_list=objs, exc_final=exc_obj, decimals=self.decimals)
  3029. app.inform.emit('[success] %s.' % _("Excellon merging finished"))
  3030. self.app_obj.new_object("excellon", 'Combo_Excellon', initialize)
  3031. self.should_we_save = True
  3032. def on_edit_join_grb(self):
  3033. """
  3034. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  3035. a new Gerber object.
  3036. :return: None
  3037. """
  3038. self.defaults.report_usage("on_edit_join_grb()")
  3039. objs = self.collection.get_selected()
  3040. for obj in objs:
  3041. if not isinstance(obj, GerberObject):
  3042. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Gerber joining works only on Gerber objects."))
  3043. return
  3044. if len(objs) < 2:
  3045. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3046. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3047. return 'fail'
  3048. def initialize(grb_obj, app):
  3049. GerberObject.merge(grb_list=objs, grb_final=grb_obj)
  3050. app.inform.emit('[success] %s.' % _("Gerber merging finished"))
  3051. self.app_obj.new_object("gerber", 'Combo_Gerber', initialize)
  3052. self.should_we_save = True
  3053. def on_convert_singlegeo_to_multigeo(self):
  3054. """
  3055. Called for converting a Geometry object from single-geo to multi-geo.
  3056. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3057. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3058. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3059. the solid-geometry of that tool.
  3060. :return: None
  3061. """
  3062. self.defaults.report_usage("on_convert_singlegeo_to_multigeo()")
  3063. obj = self.collection.get_active()
  3064. if obj is None:
  3065. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Select a Geometry Object and try again."))
  3066. return
  3067. if not isinstance(obj, GeometryObject):
  3068. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Expected a GeometryObject, got"), type(obj)))
  3069. return
  3070. obj.multigeo = True
  3071. for tooluid, dict_value in obj.tools.items():
  3072. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  3073. if not isinstance(obj.solid_geometry, list):
  3074. obj.solid_geometry = [obj.solid_geometry]
  3075. # obj.solid_geometry[:] = []
  3076. obj.plot()
  3077. self.should_we_save = True
  3078. self.inform.emit('[success] %s' % _("A Geometry object was converted to MultiGeo type."))
  3079. def on_convert_multigeo_to_singlegeo(self):
  3080. """
  3081. Called for converting a Geometry object from multi-geo to single-geo.
  3082. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3083. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3084. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3085. the solid-geometry of that tool.
  3086. :return: None
  3087. """
  3088. self.defaults.report_usage("on_convert_multigeo_to_singlegeo()")
  3089. obj = self.collection.get_active()
  3090. if obj is None:
  3091. self.inform.emit('[ERROR_NOTCL] %s' %
  3092. _("Failed. Select a Geometry Object and try again."))
  3093. return
  3094. if not isinstance(obj, GeometryObject):
  3095. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  3096. (_("Expected a GeometryObject, got"), type(obj)))
  3097. return
  3098. obj.multigeo = False
  3099. total_solid_geometry = []
  3100. for tooluid, dict_value in obj.tools.items():
  3101. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  3102. # clear the original geometry
  3103. dict_value['solid_geometry'][:] = []
  3104. obj.solid_geometry = deepcopy(total_solid_geometry)
  3105. obj.plot()
  3106. self.should_we_save = True
  3107. self.inform.emit('[success] %s' %
  3108. _("A Geometry object was converted to SingleGeo type."))
  3109. def on_defaults_dict_change(self, field):
  3110. """
  3111. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  3112. Edit -> Preferences tab window.
  3113. :param field: the key of the self.defaults dictionary that was changed.
  3114. :return: None
  3115. """
  3116. self.preferencesUiManager.defaults_write_form_field(field=field)
  3117. if field == "units":
  3118. self.set_screen_units(self.defaults['units'])
  3119. def set_screen_units(self, units):
  3120. """
  3121. Set the FlatCAM units on the status bar.
  3122. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  3123. :return: None
  3124. """
  3125. self.ui.units_label.setText("[" + units.lower() + "]")
  3126. def on_toggle_units_click(self):
  3127. try:
  3128. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  3129. except (TypeError, AttributeError):
  3130. pass
  3131. if self.defaults["units"] == 'MM':
  3132. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  3133. else:
  3134. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  3135. self.on_toggle_units(no_pref=True)
  3136. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  3137. lambda: self.on_toggle_units(no_pref=False))
  3138. def on_toggle_units(self, no_pref=False):
  3139. """
  3140. Callback for the Units radio-button change in the Preferences tab.
  3141. Changes the application's default units adn for the project too.
  3142. If changing the project's units, the change propagates to all of
  3143. the objects in the project.
  3144. :return: None
  3145. """
  3146. self.defaults.report_usage("on_toggle_units")
  3147. if self.toggle_units_ignore:
  3148. return
  3149. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3150. # If option is the same, then ignore
  3151. if new_units == self.defaults["units"].upper():
  3152. self.log.debug("on_toggle_units(): Same as previous, ignoring.")
  3153. return
  3154. # Keys in self.defaults for which to scale their values
  3155. dimensions = ['tools_iso_tooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin',
  3156. "gerber_editor_newsize", "gerber_editor_lin_pitch", "gerber_editor_buff_f",
  3157. "tools_iso_tool_vtipdia",
  3158. "tools_iso_tool_cutz", "gerber_editor_newdim", "gerber_editor_ma_low",
  3159. "gerber_editor_ma_high",
  3160. 'excellon_cutz', 'excellon_travelz', "excellon_toolchangexy", 'excellon_offset',
  3161. 'excellon_feedrate_z', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  3162. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', 'excellon_endxy',
  3163. "excellon_feedrate_probe", "excellon_milling_dia",
  3164. "excellon_z_pdepth", "excellon_editor_newdia", "excellon_editor_lin_pitch",
  3165. "excellon_editor_slot_lin_pitch", "excellon_editor_slot_length",
  3166. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  3167. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  3168. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', 'geometry_endxy',
  3169. "geometry_extracut_length", "geometry_z_pdepth",
  3170. "geometry_feedrate_probe", "geometry_startz", "geometry_segx", "geometry_segy",
  3171. 'cncjob_tooldia',
  3172. 'tools_paintmargin', 'tools_painttooldia', "tools_paintcutz", "tools_painttipdia",
  3173. "tools_paintnewdia",
  3174. "tools_ncctools", "tools_nccmargin", "tools_ncccutz", "tools_ncctipdia",
  3175. "tools_nccnewdia", "tools_ncc_offset_value",
  3176. "tools_2sided_drilldia",
  3177. "tools_film_boundary", "tools_film_scale_stroke",
  3178. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize', "tools_cutout_z",
  3179. "tools_cutout_depthperpass",
  3180. "tools_panelize_constrainx", "tools_panelize_constrainy", "tools_panelize_spacing_columns",
  3181. "tools_panelize_spacing_rows",
  3182. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  3183. "tools_transform_offset_x", "tools_transform_offset_y", "tools_transform_mirror_point",
  3184. "tools_transform_buffer_dis",
  3185. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  3186. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  3187. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  3188. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  3189. "tools_cr_trace_size_val", "tools_cr_c2c_val", "tools_cr_c2o_val", "tools_cr_s2s_val",
  3190. "tools_cr_s2sm_val", "tools_cr_s2o_val", "tools_cr_sm2sm_val", "tools_cr_ri_val",
  3191. "tools_cr_h2h_val", "tools_cr_dh_val",
  3192. "tools_fiducials_dia", "tools_fiducials_margin", "tools_fiducials_line_thickness",
  3193. "tools_copper_thieving_clearance", "tools_copper_thieving_margin",
  3194. "tools_copper_thieving_dots_dia", "tools_copper_thieving_dots_spacing",
  3195. "tools_copper_thieving_squares_size", "tools_copper_thieving_squares_spacing",
  3196. "tools_copper_thieving_lines_size", "tools_copper_thieving_lines_spacing",
  3197. "tools_copper_thieving_rb_margin", "tools_copper_thieving_rb_thickness",
  3198. "tools_copper_thieving_mask_clearance",
  3199. "tools_cal_travelz", "tools_cal_verz", "tools_cal_toolchangez", "tools_cal_toolchange_xy",
  3200. "tools_edrills_hole_fixed_dia", "tools_edrills_circular_ring", "tools_edrills_oblong_ring",
  3201. "tools_edrills_square_ring", "tools_edrills_rectangular_ring", "tools_edrills_others_ring",
  3202. "tools_punch_hole_fixed_dia", "tools_punch_circular_ring", "tools_punch_oblong_ring",
  3203. "tools_punch_square_ring", "tools_punch_rectangular_ring", "tools_punch_others_ring",
  3204. "tools_invert_margin",
  3205. 'global_gridx', 'global_gridy', 'global_snap_max', "global_tolerance",
  3206. 'global_tpdf_bmargin', 'global_tpdf_tmargin', 'global_tpdf_rmargin', 'global_tpdf_lmargin']
  3207. def scale_defaults(sfactor):
  3208. for dim in dimensions:
  3209. if dim in [
  3210. 'gerber_editor_newdim', 'excellon_toolchangexy', 'geometry_toolchangexy', 'excellon_endxy',
  3211. 'geometry_endxy', 'tools_solderpaste_xy_toolchange', 'tools_cal_toolchange_xy',
  3212. 'tools_transform_mirror_point'
  3213. ]:
  3214. if self.defaults[dim] is None or self.defaults[dim] == '':
  3215. continue
  3216. try:
  3217. coordinates = self.defaults[dim].split(",")
  3218. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3219. coords_xy[0] *= sfactor
  3220. coords_xy[1] *= sfactor
  3221. self.defaults[dim] = "%.*f, %.*f" % (
  3222. self.decimals, coords_xy[0], self.decimals, coords_xy[1])
  3223. except Exception as e:
  3224. log.debug("App.on_toggle_units.scale_defaults() --> 'string tuples': %s" % str(e))
  3225. elif dim in [
  3226. 'geometry_cnctooldia', 'tools_ncctools', 'tools_solderpaste_tools'
  3227. ]:
  3228. if self.defaults[dim] is None or self.defaults[dim] == '':
  3229. continue
  3230. try:
  3231. self.defaults[dim] = float(self.defaults[dim])
  3232. tools_diameters = [self.defaults[dim]]
  3233. except ValueError:
  3234. try:
  3235. tools_string = self.defaults[dim].split(",")
  3236. tools_diameters = [eval(a) for a in tools_string if a != '']
  3237. except Exception as e:
  3238. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3239. continue
  3240. self.defaults[dim] = ''
  3241. td_len = len(tools_diameters)
  3242. if td_len > 1:
  3243. for t in range(td_len):
  3244. tools_diameters[t] *= sfactor
  3245. self.defaults[dim] += "%.*f," % (self.decimals, tools_diameters[t])
  3246. else:
  3247. tools_diameters[0] *= sfactor
  3248. self.defaults[dim] += "%.*f" % (self.decimals, tools_diameters[0])
  3249. elif dim in ['global_gridx', 'global_gridy']:
  3250. # format the number of decimals to the one specified in self.decimals
  3251. try:
  3252. val = float(self.defaults[dim]) * sfactor
  3253. except Exception as e:
  3254. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3255. continue
  3256. self.defaults[dim] = float('%.*f' % (self.decimals, val))
  3257. else:
  3258. # the number of decimals for the rest is kept unchanged
  3259. if self.defaults[dim]:
  3260. try:
  3261. val = float(self.defaults[dim]) * sfactor
  3262. except Exception as e:
  3263. log.debug('App.on_toggle_units().scale_defaults() --> Value: %s %s' % (str(dim), str(e)))
  3264. continue
  3265. self.defaults[dim] = val
  3266. # The scaling factor depending on choice of units.
  3267. factor = 25.4 if new_units == 'MM' else 1 / 25.4
  3268. # Changing project units. Warn user.
  3269. msgbox = QtWidgets.QMessageBox()
  3270. msgbox.setWindowTitle(_("Toggle Units"))
  3271. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/toggle_units32.png'))
  3272. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  3273. msgbox.setText(_("Changing the units of the project\n"
  3274. "will scale all objects.\n\n"
  3275. "Do you want to continue?"))
  3276. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3277. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3278. msgbox.setDefaultButton(bt_ok)
  3279. msgbox.exec_()
  3280. response = msgbox.clickedButton()
  3281. if response == bt_ok:
  3282. if no_pref is False:
  3283. self.preferencesUiManager.defaults_read_form()
  3284. scale_defaults(factor)
  3285. self.preferencesUiManager.defaults_write_form(fl_units=new_units)
  3286. self.defaults["units"] = new_units
  3287. # update the defaults from form, some may assume that the conversion is enough and it's not
  3288. self.on_options_app2project()
  3289. # update the objects
  3290. for obj in self.collection.get_list():
  3291. obj.convert_units(new_units)
  3292. # make that the properties stored in the object are also updated
  3293. self.app_obj.object_changed.emit(obj)
  3294. # rebuild the object UI
  3295. obj.build_ui()
  3296. # change this only if the workspace is active
  3297. if self.defaults['global_workspace'] is True:
  3298. self.plotcanvas.draw_workspace(pagesize=self.defaults['global_workspaceT'])
  3299. # adjust the grid values on the main toolbar
  3300. val_x = float(self.defaults['global_gridx']) * factor
  3301. val_y = val_x if self.ui.grid_gap_link_cb.isChecked() else float(self.defaults['global_gridx']) * factor
  3302. current = self.collection.get_active()
  3303. if current is not None:
  3304. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  3305. if not isinstance(current, GeometryObject):
  3306. current.to_form()
  3307. # replot all objects
  3308. self.plot_all()
  3309. # set the status labels to reflect the current FlatCAM units
  3310. self.set_screen_units(new_units)
  3311. # signal to the app that we changed the object properties and it should save the project
  3312. self.should_we_save = True
  3313. self.inform.emit('[success] %s: %s' % (_("Converted units to"), new_units))
  3314. else:
  3315. # Undo toggling
  3316. self.toggle_units_ignore = True
  3317. if self.defaults['units'].upper() == 'MM':
  3318. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  3319. else:
  3320. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  3321. self.toggle_units_ignore = False
  3322. # store the grid values so they are not changed in the next step
  3323. val_x = float(self.defaults['global_gridx'])
  3324. val_y = float(self.defaults['global_gridy'])
  3325. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  3326. self.preferencesUiManager.defaults_read_form()
  3327. # the self.preferencesUiManager.defaults_read_form() will update all defaults values
  3328. # in self.defaults from the GUI elements but
  3329. # I don't want it for the grid values, so I update them here
  3330. self.defaults['global_gridx'] = val_x
  3331. self.defaults['global_gridy'] = val_y
  3332. self.ui.grid_gap_x_entry.set_value(val_x, decimals=self.decimals)
  3333. self.ui.grid_gap_y_entry.set_value(val_y, decimals=self.decimals)
  3334. def on_tab_rmb_click(self, checked):
  3335. self.ui.notebook.set_detachable(val=checked)
  3336. self.defaults["global_tabs_detachable"] = checked
  3337. self.ui.plot_tab_area.set_detachable(val=checked)
  3338. self.defaults["global_tabs_detachable"] = checked
  3339. def on_tab_setup_context_menu(self):
  3340. initial_checked = self.defaults["global_tabs_detachable"]
  3341. action_name = str(_("Detachable Tabs"))
  3342. action = QtWidgets.QAction(self)
  3343. action.setCheckable(True)
  3344. action.setText(action_name)
  3345. action.setChecked(initial_checked)
  3346. self.ui.notebook.tabBar.addAction(action)
  3347. self.ui.plot_tab_area.tabBar.addAction(action)
  3348. try:
  3349. action.triggered.disconnect()
  3350. except TypeError:
  3351. pass
  3352. action.triggered.connect(self.on_tab_rmb_click)
  3353. def on_deselect_all(self):
  3354. self.collection.set_all_inactive()
  3355. self.delete_selection_shape()
  3356. def on_workspace_modified(self):
  3357. # self.save_defaults(silent=True)
  3358. self.plotcanvas.delete_workspace()
  3359. self.preferencesUiManager.defaults_read_form()
  3360. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  3361. def on_workspace(self):
  3362. if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value():
  3363. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  3364. self.inform[str, bool].emit(_("Workspace enabled."), False)
  3365. else:
  3366. self.plotcanvas.delete_workspace()
  3367. self.inform[str, bool].emit(_("Workspace disabled."), False)
  3368. self.preferencesUiManager.defaults_read_form()
  3369. # self.save_defaults(silent=True)
  3370. def on_workspace_toggle(self):
  3371. state = False if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value() else True
  3372. try:
  3373. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.disconnect(self.on_workspace)
  3374. except TypeError:
  3375. pass
  3376. self.ui.general_defaults_form.general_app_set_group.workspace_cb.set_value(state)
  3377. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  3378. self.on_workspace()
  3379. def on_cursor_type(self, val):
  3380. """
  3381. :param val: type of mouse cursor, set in Preferences ('small' or 'big')
  3382. :return: None
  3383. """
  3384. self.app_cursor.enabled = False
  3385. if val == 'small':
  3386. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(False)
  3387. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(False)
  3388. self.app_cursor = self.plotcanvas.new_cursor()
  3389. else:
  3390. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(True)
  3391. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(True)
  3392. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  3393. if self.ui.grid_snap_btn.isChecked():
  3394. self.app_cursor.enabled = True
  3395. else:
  3396. self.app_cursor.enabled = False
  3397. def on_tool_add_keypress(self):
  3398. # ## Current application units in Upper Case
  3399. self.units = self.defaults['units'].upper()
  3400. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3401. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  3402. if notebook_widget_name == 'selected_tab':
  3403. if self.collection.get_active().kind == 'geometry':
  3404. # Tool add works for Geometry only if Advanced is True in Preferences
  3405. if self.defaults["global_app_level"] == 'a':
  3406. tool_add_popup = FCInputDialog(title="New Tool ...",
  3407. text='Enter a Tool Diameter:',
  3408. min=0.0000, max=99.9999, decimals=4)
  3409. tool_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/letter_t_32.png'))
  3410. val, ok = tool_add_popup.get_value()
  3411. if ok:
  3412. if float(val) == 0:
  3413. self.inform.emit('[WARNING_NOTCL] %s' %
  3414. _("Please enter a tool diameter with non-zero value, in Float format."))
  3415. return
  3416. self.collection.get_active().on_tool_add(dia=float(val))
  3417. else:
  3418. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding Tool cancelled"))
  3419. else:
  3420. msgbox = QtWidgets.QMessageBox()
  3421. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  3422. "Go to Preferences -> General - Show Advanced Options."))
  3423. msgbox.setWindowTitle("Tool adding ...")
  3424. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/warning.png'))
  3425. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  3426. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3427. msgbox.setDefaultButton(bt_ok)
  3428. msgbox.exec_()
  3429. # work only if the notebook tab on focus is the Tools_Tab
  3430. if notebook_widget_name == 'tool_tab':
  3431. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3432. # and only if the tool is NCC Tool
  3433. if tool_widget == self.ncclear_tool.toolName:
  3434. self.ncclear_tool.on_add_tool_by_key()
  3435. # and only if the tool is Paint Area Tool
  3436. elif tool_widget == self.paint_tool.toolName:
  3437. self.paint_tool.on_add_tool_by_key()
  3438. # and only if the tool is Solder Paste Dispensing Tool
  3439. elif tool_widget == self.paste_tool.toolName:
  3440. self.paste_tool.on_add_tool_by_key()
  3441. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  3442. # See description below.
  3443. def on_delete_keypress(self):
  3444. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3445. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  3446. if notebook_widget_name == 'selected_tab':
  3447. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.GeometryObject'>":
  3448. self.collection.get_active().on_tool_delete()
  3449. # work only if the notebook tab on focus is the Tools_Tab
  3450. elif notebook_widget_name == 'tool_tab':
  3451. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3452. # and only if the tool is NCC Tool
  3453. if tool_widget == self.ncclear_tool.toolName:
  3454. self.ncclear_tool.on_tool_delete()
  3455. # and only if the tool is Paint Tool
  3456. elif tool_widget == self.paint_tool.toolName:
  3457. self.paint_tool.on_tool_delete()
  3458. # and only if the tool is Solder Paste Dispensing Tool
  3459. elif tool_widget == self.paste_tool.toolName:
  3460. self.paste_tool.on_tool_delete()
  3461. else:
  3462. self.on_delete()
  3463. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  3464. # some screens you have to be careful where you hover with your mouse.
  3465. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  3466. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  3467. # Complicated, I know :)
  3468. def on_delete(self, force_deletion=False):
  3469. """
  3470. Delete the currently selected FlatCAMObjs.
  3471. :param force_deletion: used by Tcl command
  3472. :return: None
  3473. """
  3474. self.defaults.report_usage("on_delete()")
  3475. response = None
  3476. bt_ok = None
  3477. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  3478. # a geometry object before we update it.
  3479. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  3480. and self.grb_editor.editor_active is False:
  3481. if self.defaults["global_delete_confirmation"] is True and force_deletion is False:
  3482. msgbox = QtWidgets.QMessageBox()
  3483. msgbox.setWindowTitle(_("Delete objects"))
  3484. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/deleteshape32.png'))
  3485. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  3486. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  3487. msgbox.setText(_("Are you sure you want to permanently delete\n"
  3488. "the selected objects?"))
  3489. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3490. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3491. msgbox.setDefaultButton(bt_ok)
  3492. msgbox.exec_()
  3493. response = msgbox.clickedButton()
  3494. if self.defaults["global_delete_confirmation"] is False or force_deletion is True:
  3495. response = bt_ok
  3496. if response == bt_ok:
  3497. if self.collection.get_active():
  3498. self.log.debug("App.on_delete()")
  3499. for obj_active in self.collection.get_selected():
  3500. # if the deleted object is GerberObject then make sure to delete the possible mark shapes
  3501. if obj_active.kind == 'gerber':
  3502. for el in obj_active.mark_shapes:
  3503. obj_active.mark_shapes[el].clear(update=True)
  3504. obj_active.mark_shapes[el].enabled = False
  3505. # obj_active.mark_shapes[el] = None
  3506. del el
  3507. elif isinstance(obj_active, CNCJobObject):
  3508. try:
  3509. obj_active.text_col.enabled = False
  3510. del obj_active.text_col
  3511. obj_active.annotation.clear(update=True)
  3512. del obj_active.annotation
  3513. except AttributeError as e:
  3514. log.debug(
  3515. "App.on_delete() --> delete annotations on a FlatCAMCNCJob object. %s" % str(e)
  3516. )
  3517. while self.collection.get_selected():
  3518. self.delete_first_selected()
  3519. # make sure that the selection shape is deleted, too
  3520. self.delete_selection_shape()
  3521. # if there are no longer objects delete also the exclusion areas shapes
  3522. if not self.collection.get_list():
  3523. self.exc_areas.clear_shapes()
  3524. self.inform.emit('%s...' % _("Object(s) deleted"))
  3525. else:
  3526. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  3527. else:
  3528. self.inform.emit(_("Save the work in Editor and try again ..."))
  3529. def delete_first_selected(self):
  3530. # Keep this for later
  3531. try:
  3532. sel_obj = self.collection.get_active()
  3533. name = sel_obj.options["name"]
  3534. isPlotted = sel_obj.options["plot"]
  3535. except AttributeError:
  3536. self.log.debug("Nothing selected for deletion")
  3537. return
  3538. if self.is_legacy is True:
  3539. # Remove plot only if the object was plotted otherwise delaxes will fail
  3540. if isPlotted:
  3541. try:
  3542. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  3543. self.plotcanvas.figure.delaxes(self.collection.get_active().shapes.axes)
  3544. except Exception as e:
  3545. log.debug("App.delete_first_selected() --> %s" % str(e))
  3546. self.plotcanvas.auto_adjust_axes()
  3547. # Remove from dictionary
  3548. self.collection.delete_active()
  3549. # Clear form
  3550. self.setup_component_editor()
  3551. self.inform.emit('%s: %s' % (_("Object deleted"), name))
  3552. def on_set_origin(self):
  3553. """
  3554. Set the origin to the left mouse click position
  3555. :return: None
  3556. """
  3557. # display the message for the user
  3558. # and ask him to click on the desired position
  3559. self.defaults.report_usage("on_set_origin()")
  3560. def origin_replot():
  3561. def worker_task():
  3562. with self.proc_container.new('%s...' % _("Plotting")):
  3563. for obj in self.collection.get_list():
  3564. obj.plot()
  3565. self.plotcanvas.fit_view()
  3566. if self.is_legacy:
  3567. self.plotcanvas.graph_event_disconnect(self.mp_zc)
  3568. else:
  3569. self.plotcanvas.graph_event_disconnect('mouse_press', self.on_set_zero_click)
  3570. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3571. self.inform.emit(_('Click to set the origin ...'))
  3572. self.mp_zc = self.plotcanvas.graph_event_connect('mouse_press', self.on_set_zero_click)
  3573. # first disconnect it as it may have been used by something else
  3574. try:
  3575. self.replot_signal.disconnect()
  3576. except TypeError:
  3577. pass
  3578. self.replot_signal[list].connect(origin_replot)
  3579. def on_set_zero_click(self, event, location=None, noplot=False, use_thread=True):
  3580. """
  3581. :param event:
  3582. :param location:
  3583. :param noplot:
  3584. :param use_thread:
  3585. :return:
  3586. """
  3587. noplot_sig = noplot
  3588. def worker_task():
  3589. with self.proc_container.new(_("Setting Origin...")):
  3590. obj_list = self.collection.get_list()
  3591. for obj in obj_list:
  3592. obj.offset((x, y))
  3593. self.app_obj.object_changed.emit(obj)
  3594. # Update the object bounding box options
  3595. a, b, c, d = obj.bounds()
  3596. obj.options['xmin'] = a
  3597. obj.options['ymin'] = b
  3598. obj.options['xmax'] = c
  3599. obj.options['ymax'] = d
  3600. self.inform.emit('[success] %s...' % _('Origin set'))
  3601. for obj in obj_list:
  3602. out_name = obj.options["name"]
  3603. if obj.kind == 'gerber':
  3604. obj.source_file = self.export_gerber(
  3605. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3606. elif obj.kind == 'excellon':
  3607. obj.source_file = self.export_excellon(
  3608. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3609. if noplot_sig is False:
  3610. self.replot_signal.emit([])
  3611. if location is not None:
  3612. if len(location) != 2:
  3613. self.inform.emit('[ERROR_NOTCL] %s...' % _("Origin coordinates specified but incomplete."))
  3614. return 'fail'
  3615. x, y = location
  3616. if use_thread is True:
  3617. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3618. else:
  3619. worker_task()
  3620. self.should_we_save = True
  3621. return
  3622. if event is not None and event.button == 1:
  3623. if self.is_legacy is False:
  3624. event_pos = event.pos
  3625. else:
  3626. event_pos = (event.xdata, event.ydata)
  3627. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  3628. if self.grid_status():
  3629. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  3630. else:
  3631. pos = pos_canvas
  3632. x = 0 - pos[0]
  3633. y = 0 - pos[1]
  3634. if use_thread is True:
  3635. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3636. else:
  3637. worker_task()
  3638. self.should_we_save = True
  3639. def on_move2origin(self, use_thread=True):
  3640. """
  3641. Move selected objects to origin.
  3642. :param use_thread: Control if to use threaded operation. Boolean.
  3643. :return:
  3644. """
  3645. def worker_task():
  3646. with self.proc_container.new(_("Moving to Origin...")):
  3647. obj_list = self.collection.get_selected()
  3648. if not obj_list:
  3649. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  3650. return
  3651. xminlist = []
  3652. yminlist = []
  3653. # first get a bounding box to fit all
  3654. for obj in obj_list:
  3655. xmin, ymin, xmax, ymax = obj.bounds()
  3656. xminlist.append(xmin)
  3657. yminlist.append(ymin)
  3658. # get the minimum x,y for all objects selected
  3659. x = min(xminlist)
  3660. y = min(yminlist)
  3661. for obj in obj_list:
  3662. obj.offset((-x, -y))
  3663. self.app_obj.object_changed.emit(obj)
  3664. # Update the object bounding box options
  3665. a, b, c, d = obj.bounds()
  3666. obj.options['xmin'] = a
  3667. obj.options['ymin'] = b
  3668. obj.options['xmax'] = c
  3669. obj.options['ymax'] = d
  3670. for obj in obj_list:
  3671. obj.plot()
  3672. for obj in obj_list:
  3673. out_name = obj.options["name"]
  3674. if obj.kind == 'gerber':
  3675. obj.source_file = self.export_gerber(
  3676. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3677. elif obj.kind == 'excellon':
  3678. obj.source_file = self.export_excellon(
  3679. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3680. self.inform.emit('[success] %s...' % _('Origin set'))
  3681. if use_thread is True:
  3682. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3683. else:
  3684. worker_task()
  3685. self.should_we_save = True
  3686. def on_jump_to(self, custom_location=None, fit_center=True):
  3687. """
  3688. Jump to a location by setting the mouse cursor location.
  3689. :param custom_location: Jump to a specified point. (x, y) tuple.
  3690. :param fit_center: If to fit view. Boolean.
  3691. :return:
  3692. """
  3693. self.defaults.report_usage("on_jump_to()")
  3694. if not custom_location:
  3695. dia_box_location = None
  3696. try:
  3697. dia_box_location = eval(self.clipboard.text())
  3698. except Exception:
  3699. pass
  3700. if type(dia_box_location) == tuple:
  3701. dia_box_location = str(dia_box_location)
  3702. else:
  3703. dia_box_location = None
  3704. # dia_box = Dialog_box(title=_("Jump to ..."),
  3705. # label=_("Enter the coordinates in format X,Y:"),
  3706. # icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  3707. # initial_text=dia_box_location)
  3708. dia_box = DialogBoxRadio(title=_("Jump to ..."),
  3709. label=_("Enter the coordinates in format X,Y:"),
  3710. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  3711. initial_text=dia_box_location,
  3712. reference=self.defaults['global_jump_ref'])
  3713. if dia_box.ok is True:
  3714. try:
  3715. location = eval(dia_box.location)
  3716. if not isinstance(location, tuple):
  3717. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  3718. return
  3719. if dia_box.reference == 'rel':
  3720. rel_x = self.mouse[0] + location[0]
  3721. rel_y = self.mouse[1] + location[1]
  3722. location = (rel_x, rel_y)
  3723. self.defaults['global_jump_ref'] = dia_box.reference
  3724. except Exception:
  3725. return
  3726. else:
  3727. return
  3728. else:
  3729. location = custom_location
  3730. self.jump_signal.emit(location)
  3731. if fit_center:
  3732. self.plotcanvas.fit_center(loc=location)
  3733. cursor = QtGui.QCursor()
  3734. if self.is_legacy is False:
  3735. # I don't know where those differences come from but they are constant for the current
  3736. # execution of the application and they are multiples of a value around 0.0263mm.
  3737. # In a random way sometimes they are more sometimes they are less
  3738. # if units == 'MM':
  3739. # cal_factor = 0.0263
  3740. # else:
  3741. # cal_factor = 0.0263 / 25.4
  3742. cal_location = (location[0], location[1])
  3743. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3744. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  3745. j_pos = (
  3746. int(canvas_origin.x() + round(jump_loc[0])),
  3747. int(canvas_origin.y() + round(jump_loc[1]))
  3748. )
  3749. cursor.setPos(j_pos[0], j_pos[1])
  3750. else:
  3751. # find the canvas origin which is in the top left corner
  3752. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3753. # determine the coordinates for the lowest left point of the canvas
  3754. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  3755. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  3756. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  3757. # canvas) and the point (width, height) is in the top-right location
  3758. loc = self.plotcanvas.axes.transData.transform_point(location)
  3759. j_pos = (
  3760. int(x0 + loc[0]),
  3761. int(y0 - loc[1])
  3762. )
  3763. cursor.setPos(j_pos[0], j_pos[1])
  3764. self.plotcanvas.mouse = [location[0], location[1]]
  3765. if self.defaults["global_cursor_color_enabled"] is True:
  3766. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  3767. else:
  3768. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  3769. if self.grid_status():
  3770. # Update cursor
  3771. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  3772. symbol='++', edge_color=self.cursor_color_3D,
  3773. edge_width=self.defaults["global_cursor_width"],
  3774. size=self.defaults["global_cursor_size"])
  3775. # Set the relative position label
  3776. dx = location[0] - float(self.rel_point1[0])
  3777. dy = location[1] - float(self.rel_point1[1])
  3778. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  3779. "<b>Y</b>: %.4f&nbsp;" % (location[0], location[1]))
  3780. # # Set the position label
  3781. #
  3782. # self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  3783. # "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  3784. units = self.defaults["units"].lower()
  3785. self.plotcanvas.text_hud.text = \
  3786. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  3787. dx, units, dy, units, location[0], units, location[1], units)
  3788. self.inform.emit('[success] %s' % _("Done."))
  3789. return location
  3790. def on_locate(self, obj, fit_center=True):
  3791. """
  3792. Jump to one of the corners (or center) of an object by setting the mouse cursor location
  3793. :param obj: The object on which to locate certain points
  3794. :param fit_center: If to fit view. Boolean.
  3795. :return: A point location. (x, y) tuple.
  3796. """
  3797. self.defaults.report_usage("on_locate()")
  3798. if obj is None:
  3799. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  3800. return 'fail'
  3801. class DialogBoxChoice(QtWidgets.QDialog):
  3802. def __init__(self, title=None, icon=None, choice='bl'):
  3803. """
  3804. :param title: string with the window title
  3805. """
  3806. super(DialogBoxChoice, self).__init__()
  3807. self.ok = False
  3808. self.setWindowIcon(icon)
  3809. self.setWindowTitle(str(title))
  3810. self.form = QtWidgets.QFormLayout(self)
  3811. self.ref_radio = RadioSet([
  3812. {"label": _("Bottom-Left"), "value": "bl"},
  3813. {"label": _("Top-Left"), "value": "tl"},
  3814. {"label": _("Bottom-Right"), "value": "br"},
  3815. {"label": _("Top-Right"), "value": "tr"},
  3816. {"label": _("Center"), "value": "c"}
  3817. ], orientation='vertical', stretch=False)
  3818. self.ref_radio.set_value(choice)
  3819. self.form.addRow(self.ref_radio)
  3820. self.button_box = QtWidgets.QDialogButtonBox(
  3821. QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel,
  3822. Qt.Horizontal, parent=self)
  3823. self.form.addRow(self.button_box)
  3824. self.button_box.accepted.connect(self.accept)
  3825. self.button_box.rejected.connect(self.reject)
  3826. if self.exec_() == QtWidgets.QDialog.Accepted:
  3827. self.ok = True
  3828. self.location_point = self.ref_radio.get_value()
  3829. else:
  3830. self.ok = False
  3831. self.location_point = None
  3832. dia_box = DialogBoxChoice(title=_("Locate ..."),
  3833. icon=QtGui.QIcon(self.resource_location + '/locate16.png'),
  3834. choice=self.defaults['global_locate_pt'])
  3835. if dia_box.ok is True:
  3836. try:
  3837. location_point = dia_box.location_point
  3838. self.defaults['global_locate_pt'] = dia_box.location_point
  3839. except Exception:
  3840. return
  3841. else:
  3842. return
  3843. loc_b = obj.bounds()
  3844. if location_point == 'bl':
  3845. location = (loc_b[0], loc_b[1])
  3846. elif location_point == 'tl':
  3847. location = (loc_b[0], loc_b[3])
  3848. elif location_point == 'br':
  3849. location = (loc_b[2], loc_b[1])
  3850. elif location_point == 'tr':
  3851. location = (loc_b[2], loc_b[3])
  3852. else:
  3853. # center
  3854. cx = loc_b[0] + ((loc_b[2] - loc_b[0]) / 2)
  3855. cy = loc_b[1] + ((loc_b[3] - loc_b[1]) / 2)
  3856. location = (cx, cy)
  3857. self.locate_signal.emit(location, location_point)
  3858. if fit_center:
  3859. self.plotcanvas.fit_center(loc=location)
  3860. cursor = QtGui.QCursor()
  3861. if self.is_legacy is False:
  3862. # I don't know where those differences come from but they are constant for the current
  3863. # execution of the application and they are multiples of a value around 0.0263mm.
  3864. # In a random way sometimes they are more sometimes they are less
  3865. # if units == 'MM':
  3866. # cal_factor = 0.0263
  3867. # else:
  3868. # cal_factor = 0.0263 / 25.4
  3869. cal_location = (location[0], location[1])
  3870. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3871. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  3872. j_pos = (
  3873. int(canvas_origin.x() + round(jump_loc[0])),
  3874. int(canvas_origin.y() + round(jump_loc[1]))
  3875. )
  3876. cursor.setPos(j_pos[0], j_pos[1])
  3877. else:
  3878. # find the canvas origin which is in the top left corner
  3879. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3880. # determine the coordinates for the lowest left point of the canvas
  3881. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  3882. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  3883. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  3884. # canvas) and the point (width, height) is in the top-right location
  3885. loc = self.plotcanvas.axes.transData.transform_point(location)
  3886. j_pos = (
  3887. int(x0 + loc[0]),
  3888. int(y0 - loc[1])
  3889. )
  3890. cursor.setPos(j_pos[0], j_pos[1])
  3891. self.plotcanvas.mouse = [location[0], location[1]]
  3892. if self.defaults["global_cursor_color_enabled"] is True:
  3893. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  3894. else:
  3895. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  3896. if self.grid_status():
  3897. # Update cursor
  3898. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  3899. symbol='++', edge_color=self.cursor_color_3D,
  3900. edge_width=self.defaults["global_cursor_width"],
  3901. size=self.defaults["global_cursor_size"])
  3902. # Set the relative position label
  3903. self.dx = location[0] - float(self.rel_point1[0])
  3904. self.dy = location[1] - float(self.rel_point1[1])
  3905. # Set the position label
  3906. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  3907. "<b>Y</b>: %.4f&nbsp;" % (location[0], location[1]))
  3908. # self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  3909. # "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  3910. units = self.defaults["units"].lower()
  3911. self.plotcanvas.text_hud.text = \
  3912. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  3913. self.dx, units, self.dy, units, location[0], units, location[1], units)
  3914. self.inform.emit('[success] %s' % _("Done."))
  3915. return location
  3916. def on_copy_command(self):
  3917. """
  3918. Will copy a selection of objects, creating new objects.
  3919. :return:
  3920. """
  3921. self.defaults.report_usage("on_copy_command()")
  3922. def initialize(obj_init, app):
  3923. """
  3924. :param obj_init: the new object
  3925. :type obj_init: class
  3926. :param app: An instance of the App class
  3927. :type app: App
  3928. :return: None
  3929. :rtype:
  3930. """
  3931. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  3932. try:
  3933. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  3934. except AttributeError:
  3935. pass
  3936. try:
  3937. obj_init.apertures = deepcopy(obj.apertures)
  3938. except AttributeError:
  3939. pass
  3940. try:
  3941. if obj.tools:
  3942. obj_init.tools = deepcopy(obj.tools)
  3943. except Exception as err:
  3944. log.debug("App.on_copy_command() --> %s" % str(err))
  3945. try:
  3946. obj_init.source_file = deepcopy(obj.source_file)
  3947. except (AttributeError, TypeError):
  3948. pass
  3949. def initialize_excellon(obj_init, app):
  3950. obj_init.source_file = deepcopy(obj.source_file)
  3951. obj_init.tools = deepcopy(obj.tools)
  3952. # drills are offset, so they need to be deep copied
  3953. obj_init.drills = deepcopy(obj.drills)
  3954. # slots are offset, so they need to be deep copied
  3955. obj_init.slots = deepcopy(obj.slots)
  3956. obj_init.create_geometry()
  3957. def initialize_script(obj_init, app_obj):
  3958. obj_init.source_file = deepcopy(obj.source_file)
  3959. def initialize_document(obj_init, app_obj):
  3960. obj_init.source_file = deepcopy(obj.source_file)
  3961. for obj in self.collection.get_selected():
  3962. obj_name = obj.options["name"]
  3963. try:
  3964. if isinstance(obj, ExcellonObject):
  3965. self.app_obj.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  3966. elif isinstance(obj, GerberObject):
  3967. self.app_obj.new_object("gerber", str(obj_name) + "_copy", initialize)
  3968. elif isinstance(obj, GeometryObject):
  3969. self.app_obj.new_object("geometry", str(obj_name) + "_copy", initialize)
  3970. elif isinstance(obj, ScriptObject):
  3971. self.app_obj.new_object("script", str(obj_name) + "_copy", initialize_script)
  3972. elif isinstance(obj, DocumentObject):
  3973. self.app_obj.new_object("document", str(obj_name) + "_copy", initialize_document)
  3974. except Exception as e:
  3975. return "Operation failed: %s" % str(e)
  3976. def on_copy_object2(self, custom_name):
  3977. def initialize_geometry(obj_init, app):
  3978. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  3979. try:
  3980. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  3981. except AttributeError:
  3982. pass
  3983. try:
  3984. obj_init.apertures = deepcopy(obj.apertures)
  3985. except AttributeError:
  3986. pass
  3987. try:
  3988. if obj.tools:
  3989. obj_init.tools = deepcopy(obj.tools)
  3990. except Exception as ee:
  3991. log.debug("on_copy_object2() --> %s" % str(ee))
  3992. def initialize_gerber(obj_init, app):
  3993. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  3994. obj_init.apertures = deepcopy(obj.apertures)
  3995. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  3996. def initialize_excellon(obj_init, app):
  3997. obj_init.tools = deepcopy(obj.tools)
  3998. # drills are offset, so they need to be deep copied
  3999. obj_init.drills = deepcopy(obj.drills)
  4000. # slots are offset, so they need to be deep copied
  4001. obj_init.slots = deepcopy(obj.slots)
  4002. obj_init.create_geometry()
  4003. for obj in self.collection.get_selected():
  4004. obj_name = obj.options["name"]
  4005. try:
  4006. if isinstance(obj, ExcellonObject):
  4007. self.app_obj.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  4008. elif isinstance(obj, GerberObject):
  4009. self.app_obj.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  4010. elif isinstance(obj, GeometryObject):
  4011. self.app_obj.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  4012. except Exception as er:
  4013. return "Operation failed: %s" % str(er)
  4014. def on_rename_object(self, text):
  4015. """
  4016. Will rename an object.
  4017. :param text: New name for the object.
  4018. :return:
  4019. """
  4020. self.defaults.report_usage("on_rename_object()")
  4021. named_obj = self.collection.get_active()
  4022. for obj in named_obj:
  4023. if obj is list:
  4024. self.on_rename_object(text)
  4025. else:
  4026. try:
  4027. obj.options['name'] = text
  4028. except Exception as e:
  4029. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  4030. def convert_any2geo(self):
  4031. """
  4032. Will convert any object out of Gerber, Excellon, Geometry to Geometry object.
  4033. :return:
  4034. """
  4035. self.defaults.report_usage("convert_any2geo()")
  4036. def initialize(obj_init, app):
  4037. obj_init.solid_geometry = obj.solid_geometry
  4038. try:
  4039. obj_init.follow_geometry = obj.follow_geometry
  4040. except AttributeError:
  4041. pass
  4042. try:
  4043. obj_init.apertures = obj.apertures
  4044. except AttributeError:
  4045. pass
  4046. try:
  4047. if obj.tools:
  4048. obj_init.tools = obj.tools
  4049. except AttributeError:
  4050. pass
  4051. def initialize_excellon(obj_init, app):
  4052. # objs = self.collection.get_selected()
  4053. # GeometryObject.merge(objs, obj)
  4054. solid_geo = []
  4055. for tool in obj.tools:
  4056. for geo in obj.tools[tool]['solid_geometry']:
  4057. solid_geo.append(geo)
  4058. obj_init.solid_geometry = deepcopy(solid_geo)
  4059. if not self.collection.get_selected():
  4060. log.warning("App.convert_any2geo --> No object selected")
  4061. self.inform.emit('[WARNING_NOTCL] %s' %
  4062. _("No object is selected. Select an object and try again."))
  4063. return
  4064. for obj in self.collection.get_selected():
  4065. obj_name = obj.options["name"]
  4066. try:
  4067. if isinstance(obj, ExcellonObject):
  4068. self.app_obj.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  4069. else:
  4070. self.app_obj.new_object("geometry", str(obj_name) + "_conv", initialize)
  4071. except Exception as e:
  4072. return "Operation failed: %s" % str(e)
  4073. def convert_any2gerber(self):
  4074. """
  4075. Will convert any object out of Gerber, Excellon, Geometry to Gerber object.
  4076. :return:
  4077. """
  4078. self.defaults.report_usage("convert_any2gerber()")
  4079. def initialize_geometry(obj_init, app):
  4080. apertures = {}
  4081. apid = 0
  4082. apertures[str(apid)] = {}
  4083. apertures[str(apid)]['geometry'] = []
  4084. for obj_orig in obj.solid_geometry:
  4085. new_elem = {}
  4086. new_elem['solid'] = obj_orig
  4087. try:
  4088. new_elem['follow'] = obj_orig.exterior
  4089. except AttributeError:
  4090. pass
  4091. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  4092. apertures[str(apid)]['size'] = 0.0
  4093. apertures[str(apid)]['type'] = 'C'
  4094. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4095. obj_init.apertures = deepcopy(apertures)
  4096. def initialize_excellon(obj_init, app):
  4097. apertures = {}
  4098. apid = 10
  4099. for tool in obj.tools:
  4100. apertures[str(apid)] = {}
  4101. apertures[str(apid)]['geometry'] = []
  4102. for geo in obj.tools[tool]['solid_geometry']:
  4103. new_el = {}
  4104. new_el['solid'] = geo
  4105. new_el['follow'] = geo.exterior
  4106. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  4107. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  4108. apertures[str(apid)]['type'] = 'C'
  4109. apid += 1
  4110. # create solid_geometry
  4111. solid_geometry = []
  4112. for apid in apertures:
  4113. for geo_el in apertures[apid]['geometry']:
  4114. solid_geometry.append(geo_el['solid'])
  4115. solid_geometry = MultiPolygon(solid_geometry)
  4116. solid_geometry = solid_geometry.buffer(0.0000001)
  4117. obj_init.solid_geometry = deepcopy(solid_geometry)
  4118. obj_init.apertures = deepcopy(apertures)
  4119. # clear the working objects (perhaps not necessary due of Python GC)
  4120. apertures.clear()
  4121. if not self.collection.get_selected():
  4122. log.warning("App.convert_any2gerber --> No object selected")
  4123. self.inform.emit('[WARNING_NOTCL] %s' %
  4124. _("No object is selected. Select an object and try again."))
  4125. return
  4126. for obj in self.collection.get_selected():
  4127. obj_name = obj.options["name"]
  4128. try:
  4129. if isinstance(obj, ExcellonObject):
  4130. self.app_obj.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  4131. elif isinstance(obj, GeometryObject):
  4132. self.app_obj.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  4133. else:
  4134. log.warning("App.convert_any2gerber --> This is no vaild object for conversion.")
  4135. except Exception as e:
  4136. return "Operation failed: %s" % str(e)
  4137. def abort_all_tasks(self):
  4138. """
  4139. Executed when a certain key combo is pressed (Ctrl+Alt+X). Will abort current task
  4140. on the first possible occasion.
  4141. :return:
  4142. """
  4143. if self.abort_flag is False:
  4144. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  4145. self.abort_flag = True
  4146. self.cleanup.emit()
  4147. def app_is_idle(self):
  4148. if self.abort_flag:
  4149. self.inform.emit('[WARNING_NOTCL] %s' % _("The current task was gracefully closed on user request..."))
  4150. self.abort_flag = False
  4151. def on_selectall(self):
  4152. """
  4153. Will draw a selection box shape around the selected objects.
  4154. :return:
  4155. """
  4156. self.defaults.report_usage("on_selectall()")
  4157. # delete the possible selection box around a possible selected object
  4158. self.delete_selection_shape()
  4159. for name in self.collection.get_names():
  4160. self.collection.set_active(name)
  4161. curr_sel_obj = self.collection.get_by_name(name)
  4162. # create the selection box around the selected object
  4163. if self.defaults['global_selection_shape'] is True:
  4164. self.draw_selection_shape(curr_sel_obj)
  4165. def on_preferences(self):
  4166. """
  4167. Adds the Preferences in a Tab in Plot Area
  4168. :return:
  4169. """
  4170. # add the tab if it was closed
  4171. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  4172. # delete the absolute and relative position and messages in the infobar
  4173. self.ui.position_label.setText("")
  4174. # self.ui.rel_position_label.setText("")
  4175. # Switch plot_area to preferences page
  4176. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  4177. # self.ui.show()
  4178. # detect changes in the preferences
  4179. for idx in range(self.ui.pref_tab_area.count()):
  4180. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  4181. try:
  4182. try:
  4183. tb.textEdited.disconnect(self.preferencesUiManager.on_preferences_edited)
  4184. except (TypeError, AttributeError):
  4185. pass
  4186. tb.textEdited.connect(self.preferencesUiManager.on_preferences_edited)
  4187. except AttributeError:
  4188. pass
  4189. try:
  4190. try:
  4191. tb.modificationChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4192. except (TypeError, AttributeError):
  4193. pass
  4194. tb.modificationChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4195. except AttributeError:
  4196. pass
  4197. try:
  4198. try:
  4199. tb.toggled.disconnect(self.preferencesUiManager.on_preferences_edited)
  4200. except (TypeError, AttributeError):
  4201. pass
  4202. tb.toggled.connect(self.preferencesUiManager.on_preferences_edited)
  4203. except AttributeError:
  4204. pass
  4205. try:
  4206. try:
  4207. tb.valueChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4208. except (TypeError, AttributeError):
  4209. pass
  4210. tb.valueChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4211. except AttributeError:
  4212. pass
  4213. try:
  4214. try:
  4215. tb.currentIndexChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4216. except (TypeError, AttributeError):
  4217. pass
  4218. tb.currentIndexChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4219. except AttributeError:
  4220. pass
  4221. def on_tools_database(self, source='app'):
  4222. """
  4223. Adds the Tools Database in a Tab in Plot Area.
  4224. :return:
  4225. """
  4226. for idx in range(self.ui.plot_tab_area.count()):
  4227. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4228. # there can be only one instance of Tools Database at one time
  4229. return
  4230. if source == 'app':
  4231. self.tools_db_tab = ToolsDB2(
  4232. app=self,
  4233. parent=self.ui,
  4234. callback_on_edited=self.on_tools_db_edited,
  4235. callback_on_tool_request=self.on_geometry_tool_add_from_db_executed
  4236. )
  4237. elif source == 'ncc':
  4238. self.tools_db_tab = ToolsDB2(
  4239. app=self,
  4240. parent=self.ui,
  4241. callback_on_edited=self.on_tools_db_edited,
  4242. callback_on_tool_request=self.ncclear_tool.on_ncc_tool_add_from_db_executed
  4243. )
  4244. elif source == 'paint':
  4245. self.tools_db_tab = ToolsDB2(
  4246. app=self,
  4247. parent=self.ui,
  4248. callback_on_edited=self.on_tools_db_edited,
  4249. callback_on_tool_request=self.paint_tool.on_paint_tool_add_from_db_executed
  4250. )
  4251. elif source == 'iso':
  4252. self.tools_db_tab = ToolsDB2(
  4253. app=self,
  4254. parent=self.ui,
  4255. callback_on_edited=self.on_tools_db_edited,
  4256. callback_on_tool_request=self.isolation_tool.on_iso_tool_add_from_db_executed
  4257. )
  4258. # add the tab if it was closed
  4259. try:
  4260. self.ui.plot_tab_area.addTab(self.tools_db_tab, _("Tools Database"))
  4261. self.tools_db_tab.setObjectName("database_tab")
  4262. except Exception as e:
  4263. log.debug("App.on_tools_database() --> %s" % str(e))
  4264. return
  4265. # delete the absolute and relative position and messages in the infobar
  4266. self.ui.position_label.setText("")
  4267. # self.ui.rel_position_label.setText("")
  4268. # Switch plot_area to preferences page
  4269. self.ui.plot_tab_area.setCurrentWidget(self.tools_db_tab)
  4270. # detect changes in the Tools in Tools DB, connect signals from table widget in tab
  4271. self.tools_db_tab.ui_connect()
  4272. def on_tools_db_edited(self):
  4273. """
  4274. Executed whenever a tool is edited in Tools Database.
  4275. Will color the text of the Tools Database tab to Red color.
  4276. :return:
  4277. """
  4278. self.inform.emit('[WARNING_NOTCL] %s' % _("Tools in Tools Database edited but not saved."))
  4279. for idx in range(self.ui.plot_tab_area.count()):
  4280. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4281. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  4282. self.tools_db_tab.save_db_btn.setStyleSheet("QPushButton {color: red;}")
  4283. self.tools_db_changed_flag = True
  4284. def on_geometry_tool_add_from_db_executed(self, tool):
  4285. """
  4286. Here add the tool from DB in the selected geometry object.
  4287. :return:
  4288. """
  4289. tool_from_db = deepcopy(tool)
  4290. obj = self.collection.get_active()
  4291. if isinstance(obj, GeometryObject):
  4292. obj.on_tool_from_db_inserted(tool=tool_from_db)
  4293. # close the tab and delete it
  4294. for idx in range(self.ui.plot_tab_area.count()):
  4295. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4296. wdg = self.ui.plot_tab_area.widget(idx)
  4297. wdg.deleteLater()
  4298. self.ui.plot_tab_area.removeTab(idx)
  4299. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  4300. else:
  4301. self.inform.emit('[ERROR_NOTCL] %s' % _("Adding tool from DB is not allowed for this object."))
  4302. def on_plot_area_tab_closed(self, tab_obj_name):
  4303. """
  4304. Executed whenever a QTab is closed in the Plot Area.
  4305. :param tab_obj_name: The objectName of the Tab that was closed. This objectName is assigned on Tab creation
  4306. :return:
  4307. """
  4308. if tab_obj_name == "preferences_tab":
  4309. self.preferencesUiManager.on_close_preferences_tab()
  4310. elif tab_obj_name == "database_tab":
  4311. # disconnect the signals from the table widget in tab
  4312. self.tools_db_tab.ui_disconnect()
  4313. if self.tools_db_changed_flag is True:
  4314. msgbox = QtWidgets.QMessageBox()
  4315. msgbox.setText(_("One or more Tools are edited.\n"
  4316. "Do you want to update the Tools Database?"))
  4317. msgbox.setWindowTitle(_("Save Tools Database"))
  4318. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  4319. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  4320. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  4321. msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  4322. msgbox.setDefaultButton(bt_yes)
  4323. msgbox.exec_()
  4324. response = msgbox.clickedButton()
  4325. if response == bt_yes:
  4326. self.tools_db_tab.on_save_tools_db()
  4327. self.inform.emit('[success] %s' % "Tools DB saved to file.")
  4328. else:
  4329. self.tools_db_changed_flag = False
  4330. self.inform.emit('')
  4331. return
  4332. self.tools_db_tab.deleteLater()
  4333. elif tab_obj_name == "text_editor_tab":
  4334. self.toggle_codeeditor = False
  4335. elif tab_obj_name == "bookmarks_tab":
  4336. self.book_dialog_tab.rebuild_actions()
  4337. self.book_dialog_tab.deleteLater()
  4338. else:
  4339. return
  4340. # def on_plotarea_tab_closed(self, tab_idx):
  4341. # """
  4342. #
  4343. # :param tab_idx: Index of the Tab from the plotarea that was closed
  4344. # :return:
  4345. # """
  4346. # widget = self.ui.plot_tab_area.widget(tab_idx)
  4347. #
  4348. # if widget is not None:
  4349. # widget.deleteLater()
  4350. # self.ui.plot_tab_area.removeTab(tab_idx)
  4351. def on_flipy(self):
  4352. """
  4353. Executed when the menu entry in Options -> Flip on Y axis is clicked.
  4354. :return:
  4355. """
  4356. self.defaults.report_usage("on_flipy()")
  4357. obj_list = self.collection.get_selected()
  4358. xminlist = []
  4359. yminlist = []
  4360. xmaxlist = []
  4361. ymaxlist = []
  4362. if not obj_list:
  4363. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Flip on Y axis."))
  4364. else:
  4365. try:
  4366. # first get a bounding box to fit all
  4367. for obj in obj_list:
  4368. xmin, ymin, xmax, ymax = obj.bounds()
  4369. xminlist.append(xmin)
  4370. yminlist.append(ymin)
  4371. xmaxlist.append(xmax)
  4372. ymaxlist.append(ymax)
  4373. # get the minimum x,y and maximum x,y for all objects selected
  4374. xminimal = min(xminlist)
  4375. yminimal = min(yminlist)
  4376. xmaximal = max(xmaxlist)
  4377. ymaximal = max(ymaxlist)
  4378. px = 0.5 * (xminimal + xmaximal)
  4379. py = 0.5 * (yminimal + ymaximal)
  4380. # execute mirroring
  4381. for obj in obj_list:
  4382. obj.mirror('X', [px, py])
  4383. obj.plot()
  4384. self.app_obj.object_changed.emit(obj)
  4385. self.inform.emit('[success] %s' %
  4386. _("Flip on Y axis done."))
  4387. except Exception as e:
  4388. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  4389. return
  4390. def on_flipx(self):
  4391. """
  4392. Executed when the menu entry in Options -> Flip on X axis is clicked.
  4393. :return:
  4394. """
  4395. self.defaults.report_usage("on_flipx()")
  4396. obj_list = self.collection.get_selected()
  4397. xminlist = []
  4398. yminlist = []
  4399. xmaxlist = []
  4400. ymaxlist = []
  4401. if not obj_list:
  4402. self.inform.emit('[WARNING_NOTCL] %s' %
  4403. _("No object selected to Flip on X axis."))
  4404. else:
  4405. try:
  4406. # first get a bounding box to fit all
  4407. for obj in obj_list:
  4408. xmin, ymin, xmax, ymax = obj.bounds()
  4409. xminlist.append(xmin)
  4410. yminlist.append(ymin)
  4411. xmaxlist.append(xmax)
  4412. ymaxlist.append(ymax)
  4413. # get the minimum x,y and maximum x,y for all objects selected
  4414. xminimal = min(xminlist)
  4415. yminimal = min(yminlist)
  4416. xmaximal = max(xmaxlist)
  4417. ymaximal = max(ymaxlist)
  4418. px = 0.5 * (xminimal + xmaximal)
  4419. py = 0.5 * (yminimal + ymaximal)
  4420. # execute mirroring
  4421. for obj in obj_list:
  4422. obj.mirror('Y', [px, py])
  4423. obj.plot()
  4424. self.app_obj.object_changed.emit(obj)
  4425. self.inform.emit('[success] %s' %
  4426. _("Flip on X axis done."))
  4427. except Exception as e:
  4428. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  4429. return
  4430. def on_rotate(self, silent=False, preset=None):
  4431. """
  4432. Executed when Options -> Rotate Selection menu entry is clicked.
  4433. :param silent: If silent is True then use the preset value for the angle of the rotation.
  4434. :param preset: A value to be used as predefined angle for rotation.
  4435. :return:
  4436. """
  4437. self.defaults.report_usage("on_rotate()")
  4438. obj_list = self.collection.get_selected()
  4439. xminlist = []
  4440. yminlist = []
  4441. xmaxlist = []
  4442. ymaxlist = []
  4443. if not obj_list:
  4444. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Rotate."))
  4445. else:
  4446. if silent is False:
  4447. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4448. min=-360, max=360, decimals=4,
  4449. init_val=float(self.defaults['tools_transform_rotate']))
  4450. num, ok = rotatebox.get_value()
  4451. else:
  4452. num = preset
  4453. ok = True
  4454. if ok:
  4455. try:
  4456. # first get a bounding box to fit all
  4457. for obj in obj_list:
  4458. xmin, ymin, xmax, ymax = obj.bounds()
  4459. xminlist.append(xmin)
  4460. yminlist.append(ymin)
  4461. xmaxlist.append(xmax)
  4462. ymaxlist.append(ymax)
  4463. # get the minimum x,y and maximum x,y for all objects selected
  4464. xminimal = min(xminlist)
  4465. yminimal = min(yminlist)
  4466. xmaximal = max(xmaxlist)
  4467. ymaximal = max(ymaxlist)
  4468. px = 0.5 * (xminimal + xmaximal)
  4469. py = 0.5 * (yminimal + ymaximal)
  4470. for sel_obj in obj_list:
  4471. sel_obj.rotate(-float(num), point=(px, py))
  4472. sel_obj.plot()
  4473. self.app_obj.object_changed.emit(sel_obj)
  4474. self.inform.emit('[success] %s' % _("Rotation done."))
  4475. except Exception as e:
  4476. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Rotation movement was not executed."), str(e)))
  4477. return
  4478. def on_skewx(self):
  4479. """
  4480. Executed when the menu entry in Options -> Skew on X axis is clicked.
  4481. :return:
  4482. """
  4483. self.defaults.report_usage("on_skewx()")
  4484. obj_list = self.collection.get_selected()
  4485. xminlist = []
  4486. yminlist = []
  4487. if not obj_list:
  4488. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Skew/Shear on X axis."))
  4489. else:
  4490. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4491. min=-360, max=360, decimals=4,
  4492. init_val=float(self.defaults['tools_transform_skew_x']))
  4493. num, ok = skewxbox.get_value()
  4494. if ok:
  4495. # first get a bounding box to fit all
  4496. for obj in obj_list:
  4497. xmin, ymin, xmax, ymax = obj.bounds()
  4498. xminlist.append(xmin)
  4499. yminlist.append(ymin)
  4500. # get the minimum x,y and maximum x,y for all objects selected
  4501. xminimal = min(xminlist)
  4502. yminimal = min(yminlist)
  4503. for obj in obj_list:
  4504. obj.skew(num, 0, point=(xminimal, yminimal))
  4505. obj.plot()
  4506. self.app_obj.object_changed.emit(obj)
  4507. self.inform.emit('[success] %s' % _("Skew on X axis done."))
  4508. def on_skewy(self):
  4509. """
  4510. Executed when the menu entry in Options -> Skew on Y axis is clicked.
  4511. :return:
  4512. """
  4513. self.defaults.report_usage("on_skewy()")
  4514. obj_list = self.collection.get_selected()
  4515. xminlist = []
  4516. yminlist = []
  4517. if not obj_list:
  4518. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Skew/Shear on Y axis."))
  4519. else:
  4520. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4521. min=-360, max=360, decimals=4,
  4522. init_val=float(self.defaults['tools_transform_skew_y']))
  4523. num, ok = skewybox.get_value()
  4524. if ok:
  4525. # first get a bounding box to fit all
  4526. for obj in obj_list:
  4527. xmin, ymin, xmax, ymax = obj.bounds()
  4528. xminlist.append(xmin)
  4529. yminlist.append(ymin)
  4530. # get the minimum x,y and maximum x,y for all objects selected
  4531. xminimal = min(xminlist)
  4532. yminimal = min(yminlist)
  4533. for obj in obj_list:
  4534. obj.skew(0, num, point=(xminimal, yminimal))
  4535. obj.plot()
  4536. self.app_obj.object_changed.emit(obj)
  4537. self.inform.emit('[success] %s' % _("Skew on Y axis done."))
  4538. def on_plots_updated(self):
  4539. """
  4540. Callback used to report when the plots have changed.
  4541. Adjust axes and zooms to fit.
  4542. :return: None
  4543. """
  4544. if self.is_legacy is False:
  4545. self.plotcanvas.update()
  4546. else:
  4547. self.plotcanvas.auto_adjust_axes()
  4548. self.on_zoom_fit()
  4549. self.collection.update_view()
  4550. # self.inform.emit(_("Plots updated ..."))
  4551. def on_toolbar_replot(self):
  4552. """
  4553. Callback for toolbar button. Re-plots all objects.
  4554. :return: None
  4555. """
  4556. self.log.debug("on_toolbar_replot()")
  4557. try:
  4558. self.collection.get_active().read_form()
  4559. except AttributeError:
  4560. self.log.debug("on_toolbar_replot(): AttributeError")
  4561. pass
  4562. self.plot_all()
  4563. def grid_status(self):
  4564. return True if self.ui.grid_snap_btn.isChecked() else False
  4565. def populate_cmenu_grids(self):
  4566. units = self.defaults['units'].lower()
  4567. # for act in self.ui.cmenu_gridmenu.actions():
  4568. # act.triggered.disconnect()
  4569. self.ui.cmenu_gridmenu.clear()
  4570. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  4571. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  4572. _("Grid On/Off"))
  4573. grid_toggle.setCheckable(True)
  4574. grid_toggle.setChecked(True) if self.grid_status() else grid_toggle.setChecked(False)
  4575. self.ui.cmenu_gridmenu.addSeparator()
  4576. for grid in sorted_list:
  4577. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  4578. "%s" % str(grid))
  4579. action.triggered.connect(self.set_grid)
  4580. self.ui.cmenu_gridmenu.addSeparator()
  4581. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/plus32.png'),
  4582. _("Add"))
  4583. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/delete32.png'),
  4584. _("Delete"))
  4585. grid_add.triggered.connect(self.on_grid_add)
  4586. grid_delete.triggered.connect(self.on_grid_delete)
  4587. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  4588. def set_grid(self):
  4589. menu_action = self.sender()
  4590. assert isinstance(menu_action, QtWidgets.QAction), "Expected QAction got %s" % type(menu_action)
  4591. self.ui.grid_gap_x_entry.setText(menu_action.text())
  4592. self.ui.grid_gap_y_entry.setText(menu_action.text())
  4593. def on_grid_add(self):
  4594. # ## Current application units in lower Case
  4595. units = self.defaults['units'].lower()
  4596. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  4597. text=_('Enter a Grid Value:'),
  4598. min=0.0000, max=99.9999, decimals=4)
  4599. grid_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/plus32.png'))
  4600. val, ok = grid_add_popup.get_value()
  4601. if ok:
  4602. if float(val) == 0:
  4603. self.inform.emit('[WARNING_NOTCL] %s' %
  4604. _("Please enter a grid value with non-zero value, in Float format."))
  4605. return
  4606. else:
  4607. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  4608. self.defaults["global_grid_context_menu"][str(units)].append(val)
  4609. self.inform.emit('[success] %s...' % _("New Grid added"))
  4610. else:
  4611. self.inform.emit('[WARNING_NOTCL] %s...' % _("Grid already exists"))
  4612. else:
  4613. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding New Grid cancelled"))
  4614. def on_grid_delete(self):
  4615. # ## Current application units in lower Case
  4616. units = self.defaults['units'].lower()
  4617. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  4618. text='Enter a Grid Value:',
  4619. min=0.0000, max=99.9999, decimals=4)
  4620. grid_del_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/delete32.png'))
  4621. val, ok = grid_del_popup.get_value()
  4622. if ok:
  4623. if float(val) == 0:
  4624. self.inform.emit('[WARNING_NOTCL] %s' %
  4625. _("Please enter a grid value with non-zero value, in Float format."))
  4626. return
  4627. else:
  4628. try:
  4629. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  4630. except ValueError:
  4631. self.inform.emit('[ERROR_NOTCL]%s...' % _(" Grid Value does not exist"))
  4632. return
  4633. self.inform.emit('[success] %s...' % _("Grid Value deleted"))
  4634. else:
  4635. self.inform.emit('[WARNING_NOTCL] %s...' % _("Delete Grid value cancelled"))
  4636. def on_shortcut_list(self):
  4637. self.defaults.report_usage("on_shortcut_list()")
  4638. # add the tab if it was closed
  4639. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  4640. # delete the absolute and relative position and messages in the infobar
  4641. self.ui.position_label.setText("")
  4642. # self.ui.rel_position_label.setText("")
  4643. # Switch plot_area to preferences page
  4644. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  4645. # self.ui.show()
  4646. def on_select_tab(self, name):
  4647. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  4648. if self.ui.splitter.sizes()[0] == 0:
  4649. self.ui.splitter.setSizes([1, 1])
  4650. else:
  4651. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  4652. self.ui.splitter.setSizes([0, 1])
  4653. if name == 'project':
  4654. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  4655. elif name == 'selected':
  4656. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  4657. elif name == 'tool':
  4658. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  4659. def on_copy_name(self):
  4660. self.defaults.report_usage("on_copy_name()")
  4661. obj = self.collection.get_active()
  4662. try:
  4663. name = obj.options["name"]
  4664. except AttributeError:
  4665. log.debug("on_copy_name() --> No object selected to copy it's name")
  4666. self.inform.emit('[WARNING_NOTCL]%s' %
  4667. _(" No object selected to copy it's name"))
  4668. return
  4669. self.clipboard.setText(name)
  4670. self.inform.emit(_("Name copied on clipboard ..."))
  4671. def on_mouse_click_over_plot(self, event):
  4672. """
  4673. Default actions are:
  4674. :param event: Contains information about the event, like which button
  4675. was clicked, the pixel coordinates and the axes coordinates.
  4676. :return: None
  4677. """
  4678. self.pos = []
  4679. if self.is_legacy is False:
  4680. event_pos = event.pos
  4681. # pan_button = 2 if self.defaults["global_pan_button"] == '2'else 3
  4682. # # Set the mouse button for panning
  4683. # self.plotcanvas.view.camera.pan_button_setting = pan_button
  4684. else:
  4685. event_pos = (event.xdata, event.ydata)
  4686. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  4687. # pan_button = 3 if self.defaults["global_pan_button"] == '2' else 2
  4688. # So it can receive key presses
  4689. self.plotcanvas.native.setFocus()
  4690. self.pos_canvas = self.plotcanvas.translate_coords(event_pos)
  4691. if self.grid_status():
  4692. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  4693. else:
  4694. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  4695. try:
  4696. if event.button == 1:
  4697. # Reset here the relative coordinates so there is a new reference on the click position
  4698. if self.rel_point1 is None:
  4699. self.rel_point1 = self.pos
  4700. else:
  4701. self.rel_point2 = copy(self.rel_point1)
  4702. self.rel_point1 = self.pos
  4703. self.on_mouse_move_over_plot(event, origin_click=True)
  4704. except Exception as e:
  4705. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  4706. def on_mouse_double_click_over_plot(self, event):
  4707. if event.button == 1:
  4708. self.doubleclick = True
  4709. def on_mouse_move_over_plot(self, event, origin_click=None):
  4710. """
  4711. Callback for the mouse motion event over the plot.
  4712. :param event: Contains information about the event.
  4713. :param origin_click
  4714. :return: None
  4715. """
  4716. if self.is_legacy is False:
  4717. event_pos = event.pos
  4718. if self.defaults["global_pan_button"] == '2':
  4719. pan_button = 2
  4720. else:
  4721. pan_button = 3
  4722. self.event_is_dragging = event.is_dragging
  4723. else:
  4724. event_pos = (event.xdata, event.ydata)
  4725. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  4726. if self.defaults["global_pan_button"] == '2':
  4727. pan_button = 3
  4728. else:
  4729. pan_button = 2
  4730. self.event_is_dragging = self.plotcanvas.is_dragging
  4731. # So it can receive key presses but not when the Tcl Shell is active
  4732. if not self.ui.shell_dock.isVisible():
  4733. if not self.plotcanvas.native.hasFocus():
  4734. self.plotcanvas.native.setFocus()
  4735. self.pos_jump = event_pos
  4736. self.ui.popMenu.mouse_is_panning = False
  4737. if origin_click is None:
  4738. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  4739. if event.button == pan_button and self.event_is_dragging == 1:
  4740. # if a popup menu is active don't change mouse_is_panning variable because is not True
  4741. if self.ui.popMenu.popup_active:
  4742. self.ui.popMenu.popup_active = False
  4743. return
  4744. self.ui.popMenu.mouse_is_panning = True
  4745. return
  4746. if self.rel_point1 is not None:
  4747. try: # May fail in case mouse not within axes
  4748. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  4749. if pos_canvas[0] is None or pos_canvas[1] is None:
  4750. return
  4751. if self.grid_status():
  4752. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  4753. # Update cursor
  4754. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  4755. symbol='++', edge_color=self.cursor_color_3D,
  4756. edge_width=self.defaults["global_cursor_width"],
  4757. size=self.defaults["global_cursor_size"])
  4758. else:
  4759. pos = (pos_canvas[0], pos_canvas[1])
  4760. self.dx = pos[0] - float(self.rel_point1[0])
  4761. self.dy = pos[1] - float(self.rel_point1[1])
  4762. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4763. "<b>Y</b>: %.4f&nbsp;" % (pos[0], pos[1]))
  4764. # self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4765. # "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  4766. units = self.defaults["units"].lower()
  4767. self.plotcanvas.text_hud.text = \
  4768. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  4769. self.dx, units, self.dy, units, pos[0], units, pos[1], units)
  4770. self.mouse = [pos[0], pos[1]]
  4771. # if the mouse is moved and the LMB is clicked then the action is a selection
  4772. if self.event_is_dragging == 1 and event.button == 1:
  4773. self.delete_selection_shape()
  4774. if self.dx < 0:
  4775. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  4776. face_color=self.defaults['global_alt_sel_fill'])
  4777. self.selection_type = False
  4778. elif self.dx >= 0:
  4779. self.draw_moving_selection_shape(self.pos, pos)
  4780. self.selection_type = True
  4781. else:
  4782. self.selection_type = None
  4783. else:
  4784. self.selection_type = None
  4785. # hover effect - enabled in Preferences -> General -> AppGUI Settings
  4786. if self.defaults['global_hover']:
  4787. for obj in self.collection.get_list():
  4788. try:
  4789. # select the object(s) only if it is enabled (plotted)
  4790. if obj.options['plot']:
  4791. if obj not in self.collection.get_selected():
  4792. poly_obj = Polygon(
  4793. [(obj.options['xmin'], obj.options['ymin']),
  4794. (obj.options['xmax'], obj.options['ymin']),
  4795. (obj.options['xmax'], obj.options['ymax']),
  4796. (obj.options['xmin'], obj.options['ymax'])]
  4797. )
  4798. if Point(pos).within(poly_obj):
  4799. if obj.isHovering is False:
  4800. obj.isHovering = True
  4801. obj.notHovering = True
  4802. # create the selection box around the selected object
  4803. self.draw_hover_shape(obj, color='#d1e0e0FF')
  4804. else:
  4805. if obj.notHovering is True:
  4806. obj.notHovering = False
  4807. obj.isHovering = False
  4808. self.delete_hover_shape()
  4809. except Exception:
  4810. # the Exception here will happen if we try to select on screen and we have an
  4811. # newly (and empty) just created Geometry or Excellon object that do not have the
  4812. # xmin, xmax, ymin, ymax options.
  4813. # In this case poly_obj creation (see above) will fail
  4814. pass
  4815. except Exception as e:
  4816. log.debug("App.on_mouse_move_over_plot() - rel_point1 is not None -> %s" % str(e))
  4817. self.ui.position_label.setText("")
  4818. # self.ui.rel_position_label.setText("")
  4819. self.mouse = None
  4820. def on_mouse_click_release_over_plot(self, event):
  4821. """
  4822. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  4823. and has been registered in ''self.__init__()''.
  4824. :param event: contains information about the event.
  4825. :return:
  4826. """
  4827. if self.is_legacy is False:
  4828. event_pos = event.pos
  4829. right_button = 2
  4830. else:
  4831. event_pos = (event.xdata, event.ydata)
  4832. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  4833. right_button = 3
  4834. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  4835. if self.grid_status():
  4836. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  4837. else:
  4838. pos = (pos_canvas[0], pos_canvas[1])
  4839. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  4840. # canvas menu
  4841. if event.button == right_button and self.ui.popMenu.mouse_is_panning is False: # right click
  4842. self.ui.popMenu.mouse_is_panning = False
  4843. self.cursor = QtGui.QCursor()
  4844. self.populate_cmenu_grids()
  4845. self.ui.popMenu.popup(self.cursor.pos())
  4846. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  4847. # selection and then select a type of selection ("enclosing" or "touching")
  4848. if event.button == 1: # left click
  4849. modifiers = QtWidgets.QApplication.keyboardModifiers()
  4850. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  4851. if modifiers == QtCore.Qt.ShiftModifier:
  4852. # do not auto open the Project Tab
  4853. self.click_noproject = True
  4854. self.clipboard.setText(
  4855. self.defaults["global_point_clipboard_format"] %
  4856. (self.decimals, self.pos[0], self.decimals, self.pos[1])
  4857. )
  4858. self.inform.emit('[success] %s' % _("Coordinates copied to clipboard."))
  4859. return
  4860. if self.doubleclick is True:
  4861. self.doubleclick = False
  4862. if self.collection.get_selected():
  4863. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  4864. if self.ui.splitter.sizes()[0] == 0:
  4865. self.ui.splitter.setSizes([1, 1])
  4866. try:
  4867. # delete the selection shape(S) as it may be in the way
  4868. self.delete_selection_shape()
  4869. self.delete_hover_shape()
  4870. except Exception as e:
  4871. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() double click --> Error: %s" % str(e))
  4872. return
  4873. else:
  4874. # WORKAROUND for LEGACY MODE
  4875. if self.is_legacy is True:
  4876. # if there is no move on canvas then we have no dragging selection
  4877. if self.dx == 0 or self.dy == 0:
  4878. self.selection_type = None
  4879. if self.selection_type is not None:
  4880. try:
  4881. self.selection_area_handler(self.pos, pos, self.selection_type)
  4882. self.selection_type = None
  4883. except Exception as e:
  4884. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select area --> Error: %s" % str(e))
  4885. return
  4886. else:
  4887. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  4888. if key_modifier == QtCore.Qt.ShiftModifier:
  4889. mod_key = 'Shift'
  4890. elif key_modifier == QtCore.Qt.ControlModifier:
  4891. mod_key = 'Control'
  4892. else:
  4893. mod_key = None
  4894. try:
  4895. if self.command_active is None:
  4896. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  4897. # deselect, and if it's not selected then it will be selected
  4898. # If there is no active command (self.command_active is None) then we check if we clicked
  4899. # on a object by checking the bounding limits against mouse click position
  4900. if mod_key == self.defaults["global_mselect_key"]:
  4901. self.select_objects(key='multisel')
  4902. else:
  4903. # If there is no active command (self.command_active is None) then we check if
  4904. # we clicked on a object by checking the bounding limits against mouse click position
  4905. self.select_objects()
  4906. self.delete_hover_shape()
  4907. except Exception as e:
  4908. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select click --> Error: %s" % str(e))
  4909. return
  4910. def selection_area_handler(self, start_pos, end_pos, sel_type):
  4911. """
  4912. :param start_pos: mouse position when the selection LMB click was done
  4913. :param end_pos: mouse position when the left mouse button is released
  4914. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  4915. :return:
  4916. """
  4917. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  4918. # delete previous selection shape
  4919. self.delete_selection_shape()
  4920. # make all objects inactive
  4921. self.collection.set_all_inactive()
  4922. for obj in self.collection.get_list():
  4923. try:
  4924. # select the object(s) only if it is enabled (plotted)
  4925. if obj.options['plot']:
  4926. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  4927. (obj.options['xmax'], obj.options['ymin']),
  4928. (obj.options['xmax'], obj.options['ymax']),
  4929. (obj.options['xmin'], obj.options['ymax'])])
  4930. if sel_type is True:
  4931. if poly_obj.within(poly_selection):
  4932. # create the selection box around the selected object
  4933. if self.defaults['global_selection_shape'] is True:
  4934. self.draw_selection_shape(obj)
  4935. self.collection.set_active(obj.options['name'])
  4936. else:
  4937. if poly_selection.intersects(poly_obj):
  4938. # create the selection box around the selected object
  4939. if self.defaults['global_selection_shape'] is True:
  4940. self.draw_selection_shape(obj)
  4941. self.collection.set_active(obj.options['name'])
  4942. obj.selection_shape_drawn = True
  4943. except Exception as e:
  4944. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  4945. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  4946. # In this case poly_obj creation (see above) will fail
  4947. log.debug("App.selection_area_handler() --> %s" % str(e))
  4948. def select_objects(self, key=None):
  4949. """
  4950. Will select objects clicked on canvas
  4951. :param key: for future use in cumulative selection
  4952. :return:
  4953. """
  4954. # list where we store the overlapped objects under our mouse left click position
  4955. if key is None:
  4956. self.objects_under_the_click_list = []
  4957. # Populate the list with the overlapped objects on the click position
  4958. curr_x, curr_y = self.pos
  4959. for obj in self.all_objects_list:
  4960. # ScriptObject and DocumentObject objects can't be selected
  4961. if obj.kind == 'script' or obj.kind == 'document':
  4962. continue
  4963. if key == 'multisel' and obj.options['name'] in self.objects_under_the_click_list:
  4964. continue
  4965. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  4966. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  4967. if obj.options['name'] not in self.objects_under_the_click_list:
  4968. if obj.options['plot']:
  4969. # add objects to the objects_under_the_click list only if the object is plotted
  4970. # (active and not disabled)
  4971. self.objects_under_the_click_list.append(obj.options['name'])
  4972. try:
  4973. if self.objects_under_the_click_list:
  4974. curr_sel_obj = self.collection.get_active()
  4975. # case when there is only an object under the click and we toggle it
  4976. if len(self.objects_under_the_click_list) == 1:
  4977. if curr_sel_obj is None:
  4978. self.collection.set_active(self.objects_under_the_click_list[0])
  4979. curr_sel_obj = self.collection.get_active()
  4980. # create the selection box around the selected object
  4981. if self.defaults['global_selection_shape'] is True:
  4982. self.draw_selection_shape(curr_sel_obj)
  4983. curr_sel_obj.selection_shape_drawn = True
  4984. elif curr_sel_obj.options['name'] not in self.objects_under_the_click_list:
  4985. self.collection.on_objects_selection(False)
  4986. self.delete_selection_shape()
  4987. curr_sel_obj.selection_shape_drawn = False
  4988. self.collection.set_active(self.objects_under_the_click_list[0])
  4989. curr_sel_obj = self.collection.get_active()
  4990. # create the selection box around the selected object
  4991. if self.defaults['global_selection_shape'] is True:
  4992. self.draw_selection_shape(curr_sel_obj)
  4993. curr_sel_obj.selection_shape_drawn = True
  4994. self.selected_message(curr_sel_obj=curr_sel_obj)
  4995. elif curr_sel_obj.selection_shape_drawn is False:
  4996. if self.defaults['global_selection_shape'] is True:
  4997. self.draw_selection_shape(curr_sel_obj)
  4998. curr_sel_obj.selection_shape_drawn = True
  4999. else:
  5000. self.collection.on_objects_selection(False)
  5001. self.delete_selection_shape()
  5002. if self.call_source != 'app':
  5003. self.call_source = 'app'
  5004. self.selected_message(curr_sel_obj=curr_sel_obj)
  5005. else:
  5006. # If there is no selected object
  5007. # make active the first element of the overlapped objects list
  5008. if self.collection.get_active() is None:
  5009. self.collection.set_active(self.objects_under_the_click_list[0])
  5010. self.collection.get_by_name(self.objects_under_the_click_list[0]).selection_shape_drawn = True
  5011. name_sel_obj = self.collection.get_active().options['name']
  5012. # In case that there is a selected object but it is not in the overlapped object list
  5013. # make that object inactive and activate the first element in the overlapped object list
  5014. if name_sel_obj not in self.objects_under_the_click_list:
  5015. self.collection.set_inactive(name_sel_obj)
  5016. name_sel_obj = self.objects_under_the_click_list[0]
  5017. self.collection.set_active(name_sel_obj)
  5018. else:
  5019. sel_idx = self.objects_under_the_click_list.index(name_sel_obj)
  5020. self.collection.set_all_inactive()
  5021. self.collection.set_active(
  5022. self.objects_under_the_click_list[(sel_idx + 1) % len(self.objects_under_the_click_list)])
  5023. curr_sel_obj = self.collection.get_active()
  5024. # delete the possible selection box around a possible selected object
  5025. self.delete_selection_shape()
  5026. curr_sel_obj.selection_shape_drawn = False
  5027. # create the selection box around the selected object
  5028. if self.defaults['global_selection_shape'] is True:
  5029. self.draw_selection_shape(curr_sel_obj)
  5030. curr_sel_obj.selection_shape_drawn = True
  5031. self.selected_message(curr_sel_obj=curr_sel_obj)
  5032. else:
  5033. # deselect everything
  5034. self.collection.on_objects_selection(False)
  5035. # delete the possible selection box around a possible selected object
  5036. self.delete_selection_shape()
  5037. for o in self.collection.get_list():
  5038. o.selection_shape_drawn = False
  5039. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  5040. # only when working on App
  5041. if self.call_source == 'app':
  5042. if self.click_noproject is False:
  5043. # if the Tool Tab is in focus don't change focus to Project Tab
  5044. if not self.ui.notebook.currentWidget() is self.ui.tool_tab:
  5045. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5046. else:
  5047. # restore auto open the Project Tab
  5048. self.click_noproject = False
  5049. # delete any text in the status bar, implicitly the last object name that was selected
  5050. # self.inform.emit("")
  5051. else:
  5052. self.call_source = 'app'
  5053. except Exception as e:
  5054. log.error("[ERROR] Something went bad in App.select_objects(). %s" % str(e))
  5055. def selected_message(self, curr_sel_obj):
  5056. if curr_sel_obj:
  5057. if curr_sel_obj.kind == 'gerber':
  5058. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5059. color='green',
  5060. name=str(curr_sel_obj.options['name']),
  5061. tx=_("selected"))
  5062. )
  5063. elif curr_sel_obj.kind == 'excellon':
  5064. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5065. color='brown',
  5066. name=str(curr_sel_obj.options['name']),
  5067. tx=_("selected"))
  5068. )
  5069. elif curr_sel_obj.kind == 'cncjob':
  5070. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5071. color='blue',
  5072. name=str(curr_sel_obj.options['name']),
  5073. tx=_("selected"))
  5074. )
  5075. elif curr_sel_obj.kind == 'geometry':
  5076. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5077. color='red',
  5078. name=str(curr_sel_obj.options['name']),
  5079. tx=_("selected"))
  5080. )
  5081. def delete_hover_shape(self):
  5082. self.hover_shapes.clear()
  5083. self.hover_shapes.redraw()
  5084. def draw_hover_shape(self, sel_obj, color=None):
  5085. """
  5086. :param sel_obj: The object for which the hover shape must be drawn
  5087. :param color: The color of the hover shape
  5088. :return: None
  5089. """
  5090. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5091. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5092. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5093. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5094. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  5095. if self.defaults['units'].upper() == 'MM':
  5096. hover_rect = hover_rect.buffer(-0.1)
  5097. hover_rect = hover_rect.buffer(0.2)
  5098. else:
  5099. hover_rect = hover_rect.buffer(-0.00393)
  5100. hover_rect = hover_rect.buffer(0.00787)
  5101. # if color:
  5102. # face = Color(color)
  5103. # face.alpha = 0.2
  5104. # outline = Color(color, alpha=0.8)
  5105. # else:
  5106. # face = Color(self.defaults['global_sel_fill'])
  5107. # face.alpha = 0.2
  5108. # outline = self.defaults['global_sel_line']
  5109. if color:
  5110. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5111. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5112. else:
  5113. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5114. outline = self.defaults['global_sel_line']
  5115. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  5116. if self.is_legacy is True:
  5117. self.hover_shapes.redraw()
  5118. def delete_selection_shape(self):
  5119. self.move_tool.sel_shapes.clear()
  5120. self.move_tool.sel_shapes.redraw()
  5121. def draw_selection_shape(self, sel_obj, color=None):
  5122. """
  5123. Will draw a selection shape around the selected object.
  5124. :param sel_obj: The object for which the selection shape must be drawn
  5125. :param color: The color for the selection shape.
  5126. :return: None
  5127. """
  5128. if sel_obj is None:
  5129. return
  5130. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5131. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5132. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5133. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5134. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5135. if self.defaults['units'].upper() == 'MM':
  5136. sel_rect = sel_rect.buffer(-0.1)
  5137. sel_rect = sel_rect.buffer(0.2)
  5138. else:
  5139. sel_rect = sel_rect.buffer(-0.00393)
  5140. sel_rect = sel_rect.buffer(0.00787)
  5141. if color:
  5142. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5143. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5144. else:
  5145. if self.is_legacy is False:
  5146. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5147. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  5148. else:
  5149. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.4 * 255)))[2:]
  5150. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(1.0 * 255)))[2:]
  5151. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  5152. color=outline,
  5153. face_color=face,
  5154. update=True,
  5155. layer=0,
  5156. tolerance=None))
  5157. if self.is_legacy is True:
  5158. self.move_tool.sel_shapes.redraw()
  5159. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  5160. """
  5161. Will draw a selection shape when dragging mouse on canvas.
  5162. :param old_coords: Old coordinates
  5163. :param coords: New coordinates
  5164. :param kwargs: Keyword arguments
  5165. :return:
  5166. """
  5167. if 'color' in kwargs:
  5168. color = kwargs['color']
  5169. else:
  5170. color = self.defaults['global_sel_line']
  5171. if 'face_color' in kwargs:
  5172. face_color = kwargs['face_color']
  5173. else:
  5174. face_color = self.defaults['global_sel_fill']
  5175. if 'face_alpha' in kwargs:
  5176. face_alpha = kwargs['face_alpha']
  5177. else:
  5178. face_alpha = 0.3
  5179. x0, y0 = old_coords
  5180. x1, y1 = coords
  5181. pt1 = (x0, y0)
  5182. pt2 = (x1, y0)
  5183. pt3 = (x1, y1)
  5184. pt4 = (x0, y1)
  5185. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5186. # color_t = Color(face_color)
  5187. # color_t.alpha = face_alpha
  5188. color_t = face_color[:-2] + str(hex(int(face_alpha * 255)))[2:]
  5189. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  5190. layer=0, tolerance=None)
  5191. if self.is_legacy is True:
  5192. self.move_tool.sel_shapes.redraw()
  5193. def on_file_new_click(self):
  5194. """
  5195. Callback for menu item File -> New.
  5196. Executed on clicking the Menu -> File -> New Project
  5197. :return:
  5198. """
  5199. if self.collection.get_list() and self.should_we_save:
  5200. msgbox = QtWidgets.QMessageBox()
  5201. # msgbox.setText("<B>Save changes ...</B>")
  5202. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  5203. "Creating a New project will delete them.\n"
  5204. "Do you want to Save the project?"))
  5205. msgbox.setWindowTitle(_("Save changes"))
  5206. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  5207. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  5208. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  5209. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  5210. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  5211. msgbox.setDefaultButton(bt_yes)
  5212. msgbox.exec_()
  5213. response = msgbox.clickedButton()
  5214. if response == bt_yes:
  5215. self.on_file_saveprojectas()
  5216. elif response == bt_cancel:
  5217. return
  5218. elif response == bt_no:
  5219. self.on_file_new()
  5220. else:
  5221. self.on_file_new()
  5222. self.inform.emit('[success] %s...' % _("New Project created"))
  5223. def on_file_new(self, cli=None):
  5224. """
  5225. Returns the application to its startup state. This method is thread-safe.
  5226. :param cli: Boolean. If True this method was run from command line
  5227. :return: None
  5228. """
  5229. self.defaults.report_usage("on_file_new")
  5230. # Remove everything from memory
  5231. App.log.debug("on_file_new()")
  5232. # close any editor that might be open
  5233. if self.call_source != 'app':
  5234. self.editor2object(cleanup=True)
  5235. # ## EDITOR section
  5236. self.geo_editor = FlatCAMGeoEditor(self)
  5237. self.exc_editor = FlatCAMExcEditor(self)
  5238. self.grb_editor = FlatCAMGrbEditor(self)
  5239. # Clear pool
  5240. self.clear_pool()
  5241. for obj in self.collection.get_list():
  5242. # delete shapes left drawn from mark shape_collections, if any
  5243. if isinstance(obj, GerberObject):
  5244. try:
  5245. for el in obj.mark_shapes:
  5246. obj.mark_shapes[el].clear(update=True)
  5247. obj.mark_shapes[el].enabled = False
  5248. del el
  5249. except AttributeError:
  5250. pass
  5251. # also delete annotation shapes, if any
  5252. elif isinstance(obj, CNCJobObject):
  5253. try:
  5254. obj.text_col.enabled = False
  5255. del obj.text_col
  5256. obj.annotation.clear(update=True)
  5257. del obj.annotation
  5258. except AttributeError:
  5259. pass
  5260. # delete the exclusion areas
  5261. self.exc_areas.clear_shapes()
  5262. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  5263. self.shell.init_tcl()
  5264. # delete any selection shape on canvas
  5265. self.delete_selection_shape()
  5266. # delete all FlatCAM objects
  5267. self.collection.delete_all()
  5268. # add in Selected tab an initial text that describe the flow of work in FlatCAm
  5269. self.setup_component_editor()
  5270. # Clear project filename
  5271. self.project_filename = None
  5272. # Load the application defaults
  5273. self.defaults.load(filename=os.path.join(self.data_path, 'current_defaults.FlatConfig'))
  5274. # Re-fresh project options
  5275. self.on_options_app2project()
  5276. # Init FlatCAMTools
  5277. self.init_tools()
  5278. # Try to close all tabs in the PlotArea but only if the AppGUI is active (CLI is None)
  5279. if cli is None:
  5280. # we need to go in reverse because once we remove a tab then the index changes
  5281. # meaning that removing the first tab (idx = 0) then the tab at former idx = 1 will assume idx = 0
  5282. # and so on. Therefore the deletion should be done in reverse
  5283. wdg_count = self.ui.plot_tab_area.tabBar.count() - 1
  5284. for index in range(wdg_count, -1, -1):
  5285. try:
  5286. self.ui.plot_tab_area.closeTab(index)
  5287. except Exception as e:
  5288. log.debug("App.on_file_new() --> %s" % str(e))
  5289. # # And then add again the Plot Area
  5290. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  5291. self.ui.plot_tab_area.protectTab(0)
  5292. # take the focus of the Notebook on Project Tab.
  5293. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5294. self.set_ui_title(name=_("New Project - Not saved"))
  5295. def obj_properties(self):
  5296. """
  5297. Will launch the object Properties Tool
  5298. :return:
  5299. """
  5300. self.defaults.report_usage("obj_properties()")
  5301. self.properties_tool.run(toggle=False)
  5302. def on_project_context_save(self):
  5303. """
  5304. Wrapper, will save the object function of it's type
  5305. :return:
  5306. """
  5307. obj = self.collection.get_active()
  5308. if type(obj) == GeometryObject:
  5309. self.on_file_exportdxf()
  5310. elif type(obj) == ExcellonObject:
  5311. self.on_file_saveexcellon()
  5312. elif type(obj) == CNCJobObject:
  5313. obj.on_exportgcode_button_click()
  5314. elif type(obj) == GerberObject:
  5315. self.on_file_savegerber()
  5316. elif type(obj) == ScriptObject:
  5317. self.on_file_savescript()
  5318. elif type(obj) == DocumentObject:
  5319. self.on_file_savedocument()
  5320. def obj_move(self):
  5321. """
  5322. Callback for the Move menu entry in various Context Menu's.
  5323. :return:
  5324. """
  5325. self.defaults.report_usage("obj_move()")
  5326. self.move_tool.run(toggle=False)
  5327. def on_fileopengerber(self, signal, name=None):
  5328. """
  5329. File menu callback for opening a Gerber.
  5330. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5331. :param name:
  5332. :return: None
  5333. """
  5334. self.defaults.report_usage("on_fileopengerber")
  5335. App.log.debug("on_fileopengerber()")
  5336. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *" \
  5337. ".gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  5338. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd);;" \
  5339. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  5340. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  5341. "*.mil);;" \
  5342. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  5343. "Allegro Files (*.art);;" \
  5344. "Mentor Files (*.pho *.gdo);;" \
  5345. "All Files (*.*)"
  5346. if name is None:
  5347. try:
  5348. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  5349. directory=self.get_last_folder(),
  5350. filter=_filter_)
  5351. except TypeError:
  5352. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  5353. filenames = [str(filename) for filename in filenames]
  5354. else:
  5355. filenames = [name]
  5356. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5357. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5358. _("Opening Gerber file.")),
  5359. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5360. color=QtGui.QColor("gray"))
  5361. if len(filenames) == 0:
  5362. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5363. else:
  5364. for filename in filenames:
  5365. if filename != '':
  5366. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  5367. def on_fileopenexcellon(self, signal, name=None):
  5368. """
  5369. File menu callback for opening an Excellon file.
  5370. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5371. :param name:
  5372. :return: None
  5373. """
  5374. self.defaults.report_usage("on_fileopenexcellon")
  5375. App.log.debug("on_fileopenexcellon()")
  5376. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  5377. "All Files (*.*)"
  5378. if name is None:
  5379. try:
  5380. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  5381. directory=self.get_last_folder(),
  5382. filter=_filter_)
  5383. except TypeError:
  5384. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  5385. filenames = [str(filename) for filename in filenames]
  5386. else:
  5387. filenames = [str(name)]
  5388. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5389. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5390. _("Opening Excellon file.")),
  5391. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5392. color=QtGui.QColor("gray"))
  5393. if len(filenames) == 0:
  5394. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  5395. else:
  5396. for filename in filenames:
  5397. if filename != '':
  5398. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  5399. def on_fileopengcode(self, signal, name=None):
  5400. """
  5401. File menu call back for opening gcode.
  5402. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5403. :param name:
  5404. :return:
  5405. """
  5406. self.defaults.report_usage("on_fileopengcode")
  5407. App.log.debug("on_fileopengcode()")
  5408. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  5409. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  5410. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.sbp *.mpf);;" \
  5411. "All Files (*.*)"
  5412. if name is None:
  5413. try:
  5414. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  5415. directory=self.get_last_folder(),
  5416. filter=_filter_)
  5417. except TypeError:
  5418. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  5419. filenames = [str(filename) for filename in filenames]
  5420. else:
  5421. filenames = [name]
  5422. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5423. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5424. _("Opening G-Code file.")),
  5425. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5426. color=QtGui.QColor("gray"))
  5427. if len(filenames) == 0:
  5428. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5429. else:
  5430. for filename in filenames:
  5431. if filename != '':
  5432. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename, None, True]})
  5433. def on_file_openproject(self, signal):
  5434. """
  5435. File menu callback for opening a project.
  5436. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5437. :return: None
  5438. """
  5439. self.defaults.report_usage("on_file_openproject")
  5440. App.log.debug("on_file_openproject()")
  5441. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  5442. try:
  5443. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  5444. directory=self.get_last_folder(), filter=_filter_)
  5445. except TypeError:
  5446. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  5447. # The Qt methods above will return a QString which can cause problems later.
  5448. # So far json.dump() will fail to serialize it.
  5449. # TODO: Improve the serialization methods and remove this fix.
  5450. filename = str(filename)
  5451. if filename == "":
  5452. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5453. else:
  5454. # self.worker_task.emit({'fcn': self.open_project,
  5455. # 'params': [filename]})
  5456. # The above was failing because open_project() is not
  5457. # thread safe. The new_project()
  5458. self.open_project(filename)
  5459. def on_fileopenhpgl2(self, signal, name=None):
  5460. """
  5461. File menu callback for opening a HPGL2.
  5462. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5463. :param name:
  5464. :return: None
  5465. """
  5466. self.defaults.report_usage("on_fileopenhpgl2")
  5467. App.log.debug("on_fileopenhpgl2()")
  5468. _filter_ = "HPGL2 Files (*.plt);;" \
  5469. "All Files (*.*)"
  5470. if name is None:
  5471. try:
  5472. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"),
  5473. directory=self.get_last_folder(),
  5474. filter=_filter_)
  5475. except TypeError:
  5476. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"), filter=_filter_)
  5477. filenames = [str(filename) for filename in filenames]
  5478. else:
  5479. filenames = [name]
  5480. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5481. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5482. _("Opening HPGL2 file.")),
  5483. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5484. color=QtGui.QColor("gray"))
  5485. if len(filenames) == 0:
  5486. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5487. else:
  5488. for filename in filenames:
  5489. if filename != '':
  5490. self.worker_task.emit({'fcn': self.open_hpgl2, 'params': [filename]})
  5491. def on_file_openconfig(self, signal):
  5492. """
  5493. File menu callback for opening a config file.
  5494. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5495. :return: None
  5496. """
  5497. self.defaults.report_usage("on_file_openconfig")
  5498. App.log.debug("on_file_openconfig()")
  5499. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  5500. try:
  5501. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  5502. directory=self.data_path, filter=_filter_)
  5503. except TypeError:
  5504. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  5505. filter=_filter_)
  5506. if filename == "":
  5507. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5508. else:
  5509. self.open_config_file(filename)
  5510. def on_file_exportsvg(self):
  5511. """
  5512. Callback for menu item File->Export SVG.
  5513. :return: None
  5514. """
  5515. self.defaults.report_usage("on_file_exportsvg")
  5516. App.log.debug("on_file_exportsvg()")
  5517. obj = self.collection.get_active()
  5518. if obj is None:
  5519. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5520. msg = _("Please Select a Geometry object to export")
  5521. msgbox = QtWidgets.QMessageBox()
  5522. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  5523. msgbox.setInformativeText(msg)
  5524. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5525. msgbox.setDefaultButton(bt_ok)
  5526. msgbox.exec_()
  5527. return
  5528. # Check for more compatible types and add as required
  5529. if (not isinstance(obj, GeometryObject)
  5530. and not isinstance(obj, GerberObject)
  5531. and not isinstance(obj, CNCJobObject)
  5532. and not isinstance(obj, ExcellonObject)):
  5533. msg = '[ERROR_NOTCL] %s' % \
  5534. _("Only Geometry, Gerber and CNCJob objects can be used.")
  5535. msgbox = QtWidgets.QMessageBox()
  5536. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  5537. msgbox.setInformativeText(msg)
  5538. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5539. msgbox.setDefaultButton(bt_ok)
  5540. msgbox.exec_()
  5541. return
  5542. name = obj.options["name"]
  5543. _filter = "SVG File (*.svg);;All Files (*.*)"
  5544. try:
  5545. filename, _f = FCFileSaveDialog.get_saved_filename(
  5546. caption=_("Export SVG"),
  5547. directory=self.get_last_save_folder() + '/' + str(name) + '_svg',
  5548. ext_filter=_filter)
  5549. except TypeError:
  5550. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export SVG"), ext_filter=_filter)
  5551. filename = str(filename)
  5552. if filename == "":
  5553. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  5554. return
  5555. else:
  5556. self.export_svg(name, filename)
  5557. if self.defaults["global_open_style"] is False:
  5558. self.file_opened.emit("SVG", filename)
  5559. self.file_saved.emit("SVG", filename)
  5560. def on_file_exportpng(self):
  5561. self.defaults.report_usage("on_file_exportpng")
  5562. App.log.debug("on_file_exportpng()")
  5563. self.date = str(datetime.today()).rpartition('.')[0]
  5564. self.date = ''.join(c for c in self.date if c not in ':-')
  5565. self.date = self.date.replace(' ', '_')
  5566. data = None
  5567. if self.is_legacy is False:
  5568. image = _screenshot(alpha=None)
  5569. data = np.asarray(image)
  5570. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  5571. self.inform.emit('[[WARNING_NOTCL]] %s' % _('Data must be a 3D array with last dimension 3 or 4'))
  5572. return
  5573. filter_ = "PNG File (*.png);;All Files (*.*)"
  5574. try:
  5575. filename, _f = FCFileSaveDialog.get_saved_filename(
  5576. caption=_("Export PNG Image"),
  5577. directory=self.get_last_save_folder() + '/png_' + self.date,
  5578. ext_filter=filter_)
  5579. except TypeError:
  5580. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export PNG Image"), ext_filter=filter_)
  5581. filename = str(filename)
  5582. if filename == "":
  5583. self.inform.emit(_("Cancelled."))
  5584. return
  5585. else:
  5586. if self.is_legacy is False:
  5587. write_png(filename, data)
  5588. else:
  5589. self.plotcanvas.figure.savefig(filename)
  5590. if self.defaults["global_open_style"] is False:
  5591. self.file_opened.emit("png", filename)
  5592. self.file_saved.emit("png", filename)
  5593. def on_file_savegerber(self):
  5594. """
  5595. Callback for menu item in Project context menu.
  5596. :return: None
  5597. """
  5598. self.defaults.report_usage("on_file_savegerber")
  5599. App.log.debug("on_file_savegerber()")
  5600. obj = self.collection.get_active()
  5601. if obj is None:
  5602. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5603. return
  5604. # Check for more compatible types and add as required
  5605. if not isinstance(obj, GerberObject):
  5606. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  5607. return
  5608. name = self.collection.get_active().options["name"]
  5609. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  5610. try:
  5611. filename, _f = FCFileSaveDialog.get_saved_filename(
  5612. caption="Save Gerber source file",
  5613. directory=self.get_last_save_folder() + '/' + name,
  5614. ext_filter=_filter)
  5615. except TypeError:
  5616. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Gerber source file"), ext_filter=_filter)
  5617. filename = str(filename)
  5618. if filename == "":
  5619. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5620. return
  5621. else:
  5622. self.save_source_file(name, filename)
  5623. if self.defaults["global_open_style"] is False:
  5624. self.file_opened.emit("Gerber", filename)
  5625. self.file_saved.emit("Gerber", filename)
  5626. def on_file_savescript(self):
  5627. """
  5628. Callback for menu item in Project context menu.
  5629. :return: None
  5630. """
  5631. self.defaults.report_usage("on_file_savescript")
  5632. App.log.debug("on_file_savescript()")
  5633. obj = self.collection.get_active()
  5634. if obj is None:
  5635. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5636. return
  5637. # Check for more compatible types and add as required
  5638. if not isinstance(obj, ScriptObject):
  5639. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Script objects can be saved as TCL Script files..."))
  5640. return
  5641. name = self.collection.get_active().options["name"]
  5642. _filter = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  5643. try:
  5644. filename, _f = FCFileSaveDialog.get_saved_filename(
  5645. caption="Save Script source file",
  5646. directory=self.get_last_save_folder() + '/' + name,
  5647. ext_filter=_filter)
  5648. except TypeError:
  5649. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Script source file"), ext_filter=_filter)
  5650. filename = str(filename)
  5651. if filename == "":
  5652. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5653. return
  5654. else:
  5655. self.save_source_file(name, filename)
  5656. if self.defaults["global_open_style"] is False:
  5657. self.file_opened.emit("Script", filename)
  5658. self.file_saved.emit("Script", filename)
  5659. def on_file_savedocument(self):
  5660. """
  5661. Callback for menu item in Project context menu.
  5662. :return: None
  5663. """
  5664. self.defaults.report_usage("on_file_savedocument")
  5665. App.log.debug("on_file_savedocument()")
  5666. obj = self.collection.get_active()
  5667. if obj is None:
  5668. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5669. return
  5670. # Check for more compatible types and add as required
  5671. if not isinstance(obj, ScriptObject):
  5672. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Document objects can be saved as Document files..."))
  5673. return
  5674. name = self.collection.get_active().options["name"]
  5675. _filter = "FlatCAM Documents (*.FlatDoc);;All Files (*.*)"
  5676. try:
  5677. filename, _f = FCFileSaveDialog.get_saved_filename(
  5678. caption="Save Document source file",
  5679. directory=self.get_last_save_folder() + '/' + name,
  5680. ext_filter=_filter)
  5681. except TypeError:
  5682. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Document source file"),
  5683. ext_filter=_filter)
  5684. filename = str(filename)
  5685. if filename == "":
  5686. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5687. return
  5688. else:
  5689. self.save_source_file(name, filename)
  5690. if self.defaults["global_open_style"] is False:
  5691. self.file_opened.emit("Document", filename)
  5692. self.file_saved.emit("Document", filename)
  5693. def on_file_saveexcellon(self):
  5694. """
  5695. Callback for menu item in project context menu.
  5696. :return: None
  5697. """
  5698. self.defaults.report_usage("on_file_saveexcellon")
  5699. App.log.debug("on_file_saveexcellon()")
  5700. obj = self.collection.get_active()
  5701. if obj is None:
  5702. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5703. return
  5704. # Check for more compatible types and add as required
  5705. if not isinstance(obj, ExcellonObject):
  5706. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  5707. return
  5708. name = self.collection.get_active().options["name"]
  5709. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  5710. try:
  5711. filename, _f = FCFileSaveDialog.get_saved_filename(
  5712. caption=_("Save Excellon source file"),
  5713. directory=self.get_last_save_folder() + '/' + name,
  5714. ext_filter=_filter)
  5715. except TypeError:
  5716. filename, _f = FCFileSaveDialog.get_saved_filename(
  5717. caption=_("Save Excellon source file"), ext_filter=_filter)
  5718. filename = str(filename)
  5719. if filename == "":
  5720. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5721. return
  5722. else:
  5723. self.save_source_file(name, filename)
  5724. if self.defaults["global_open_style"] is False:
  5725. self.file_opened.emit("Excellon", filename)
  5726. self.file_saved.emit("Excellon", filename)
  5727. def on_file_exportexcellon(self):
  5728. """
  5729. Callback for menu item File->Export->Excellon.
  5730. :return: None
  5731. """
  5732. self.defaults.report_usage("on_file_exportexcellon")
  5733. App.log.debug("on_file_exportexcellon()")
  5734. obj = self.collection.get_active()
  5735. if obj is None:
  5736. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5737. return
  5738. # Check for more compatible types and add as required
  5739. if not isinstance(obj, ExcellonObject):
  5740. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  5741. return
  5742. name = self.collection.get_active().options["name"]
  5743. _filter = self.defaults["excellon_save_filters"]
  5744. try:
  5745. filename, _f = FCFileSaveDialog.get_saved_filename(
  5746. caption=_("Export Excellon"),
  5747. directory=self.get_last_save_folder() + '/' + name,
  5748. ext_filter=_filter)
  5749. except TypeError:
  5750. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Excellon"), ext_filter=_filter)
  5751. filename = str(filename)
  5752. if filename == "":
  5753. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5754. return
  5755. else:
  5756. used_extension = filename.rpartition('.')[2]
  5757. obj.update_filters(last_ext=used_extension, filter_string='excellon_save_filters')
  5758. self.export_excellon(name, filename)
  5759. if self.defaults["global_open_style"] is False:
  5760. self.file_opened.emit("Excellon", filename)
  5761. self.file_saved.emit("Excellon", filename)
  5762. def on_file_exportgerber(self):
  5763. """
  5764. Callback for menu item File->Export->Gerber.
  5765. :return: None
  5766. """
  5767. self.defaults.report_usage("on_file_exportgerber")
  5768. App.log.debug("on_file_exportgerber()")
  5769. obj = self.collection.get_active()
  5770. if obj is None:
  5771. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5772. return
  5773. # Check for more compatible types and add as required
  5774. if not isinstance(obj, GerberObject):
  5775. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  5776. return
  5777. name = self.collection.get_active().options["name"]
  5778. _filter_ = self.defaults['gerber_save_filters']
  5779. try:
  5780. filename, _f = FCFileSaveDialog.get_saved_filename(
  5781. caption=_("Export Gerber"),
  5782. directory=self.get_last_save_folder() + '/' + name,
  5783. ext_filter=_filter_)
  5784. except TypeError:
  5785. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Gerber"), ext_filter=_filter_)
  5786. filename = str(filename)
  5787. if filename == "":
  5788. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5789. return
  5790. else:
  5791. used_extension = filename.rpartition('.')[2]
  5792. obj.update_filters(last_ext=used_extension, filter_string='gerber_save_filters')
  5793. self.export_gerber(name, filename)
  5794. if self.defaults["global_open_style"] is False:
  5795. self.file_opened.emit("Gerber", filename)
  5796. self.file_saved.emit("Gerber", filename)
  5797. def on_file_exportdxf(self):
  5798. """
  5799. Callback for menu item File->Export DXF.
  5800. :return: None
  5801. """
  5802. self.defaults.report_usage("on_file_exportdxf")
  5803. App.log.debug("on_file_exportdxf()")
  5804. obj = self.collection.get_active()
  5805. if obj is None:
  5806. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5807. msg = _("Please Select a Geometry object to export")
  5808. msgbox = QtWidgets.QMessageBox()
  5809. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  5810. msgbox.setInformativeText(msg)
  5811. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5812. msgbox.setDefaultButton(bt_ok)
  5813. msgbox.exec_()
  5814. return
  5815. # Check for more compatible types and add as required
  5816. if not isinstance(obj, GeometryObject):
  5817. msg = '[ERROR_NOTCL] %s' % _("Only Geometry objects can be used.")
  5818. msgbox = QtWidgets.QMessageBox()
  5819. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  5820. msgbox.setInformativeText(msg)
  5821. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5822. msgbox.setDefaultButton(bt_ok)
  5823. msgbox.exec_()
  5824. return
  5825. name = self.collection.get_active().options["name"]
  5826. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  5827. try:
  5828. filename, _f = FCFileSaveDialog.get_saved_filename(
  5829. caption=_("Export DXF"),
  5830. directory=self.get_last_save_folder() + '/' + name,
  5831. ext_filter=_filter_)
  5832. except TypeError:
  5833. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export DXF"), ext_filter=_filter_)
  5834. filename = str(filename)
  5835. if filename == "":
  5836. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5837. return
  5838. else:
  5839. self.export_dxf(name, filename)
  5840. if self.defaults["global_open_style"] is False:
  5841. self.file_opened.emit("DXF", filename)
  5842. self.file_saved.emit("DXF", filename)
  5843. def on_file_importsvg(self, type_of_obj):
  5844. """
  5845. Callback for menu item File->Import SVG.
  5846. :param type_of_obj: to import the SVG as Geometry or as Gerber
  5847. :type type_of_obj: str
  5848. :return: None
  5849. """
  5850. self.defaults.report_usage("on_file_importsvg")
  5851. App.log.debug("on_file_importsvg()")
  5852. _filter_ = "SVG File .svg (*.svg);;All Files (*.*)"
  5853. try:
  5854. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  5855. directory=self.get_last_folder(), filter=_filter_)
  5856. except TypeError:
  5857. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  5858. filter=_filter_)
  5859. if type_of_obj != "geometry" and type_of_obj != "gerber":
  5860. type_of_obj = "geometry"
  5861. filenames = [str(filename) for filename in filenames]
  5862. if len(filenames) == 0:
  5863. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5864. else:
  5865. for filename in filenames:
  5866. if filename != '':
  5867. self.worker_task.emit({'fcn': self.import_svg,
  5868. 'params': [filename, type_of_obj]})
  5869. def on_file_importdxf(self, type_of_obj):
  5870. """
  5871. Callback for menu item File->Import DXF.
  5872. :param type_of_obj: to import the DXF as Geometry or as Gerber
  5873. :type type_of_obj: str
  5874. :return: None
  5875. """
  5876. self.defaults.report_usage("on_file_importdxf")
  5877. App.log.debug("on_file_importdxf()")
  5878. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  5879. try:
  5880. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  5881. directory=self.get_last_folder(),
  5882. filter=_filter_)
  5883. except TypeError:
  5884. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  5885. filter=_filter_)
  5886. if type_of_obj != "geometry" and type_of_obj != "gerber":
  5887. type_of_obj = "geometry"
  5888. filenames = [str(filename) for filename in filenames]
  5889. if len(filenames) == 0:
  5890. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5891. else:
  5892. for filename in filenames:
  5893. if filename != '':
  5894. self.worker_task.emit({'fcn': self.import_dxf,
  5895. 'params': [filename, type_of_obj]})
  5896. # ###############################################################################################################
  5897. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  5898. # ###############################################################################################################
  5899. def init_code_editor(self, name):
  5900. self.text_editor_tab = TextEditor(app=self, plain_text=True)
  5901. # add the tab if it was closed
  5902. self.ui.plot_tab_area.addTab(self.text_editor_tab, '%s' % name)
  5903. self.text_editor_tab.setObjectName('text_editor_tab')
  5904. # delete the absolute and relative position and messages in the infobar
  5905. self.ui.position_label.setText("")
  5906. # self.ui.rel_position_label.setText("")
  5907. # first clear previous text in text editor (if any)
  5908. self.text_editor_tab.code_editor.clear()
  5909. self.text_editor_tab.code_editor.setReadOnly(False)
  5910. self.toggle_codeeditor = True
  5911. self.text_editor_tab.code_editor.completer_enable = False
  5912. self.text_editor_tab.buttonRun.hide()
  5913. # make sure to keep a reference to the code editor
  5914. self.reference_code_editor = self.text_editor_tab.code_editor
  5915. # Switch plot_area to CNCJob tab
  5916. self.ui.plot_tab_area.setCurrentWidget(self.text_editor_tab)
  5917. def on_view_source(self):
  5918. """
  5919. Called when the user wants to see the source file of the selected object
  5920. :return:
  5921. """
  5922. self.inform.emit('%s' % _("Viewing the source code of the selected object."))
  5923. self.proc_container.view.set_busy(_("Loading..."))
  5924. try:
  5925. obj = self.collection.get_active()
  5926. except Exception as e:
  5927. log.debug("App.on_view_source() --> %s" % str(e))
  5928. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  5929. return 'fail'
  5930. if obj is None:
  5931. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  5932. return 'fail'
  5933. flt = "All Files (*.*)"
  5934. if obj.kind == 'gerber':
  5935. flt = "Gerber Files .gbr (*.GBR);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  5936. elif obj.kind == 'excellon':
  5937. flt = "Excellon Files .drl (*.DRL);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  5938. elif obj.kind == 'cncjob':
  5939. flt = "GCode Files .nc (*.NC);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  5940. self.source_editor_tab = TextEditor(app=self, plain_text=True)
  5941. # add the tab if it was closed
  5942. self.ui.plot_tab_area.addTab(self.source_editor_tab, '%s' % _("Source Editor"))
  5943. self.source_editor_tab.setObjectName('source_editor_tab')
  5944. # delete the absolute and relative position and messages in the infobar
  5945. self.ui.position_label.setText("")
  5946. # self.ui.rel_position_label.setText("")
  5947. # first clear previous text in text editor (if any)
  5948. self.source_editor_tab.code_editor.clear()
  5949. self.source_editor_tab.code_editor.setReadOnly(False)
  5950. self.source_editor_tab.code_editor.completer_enable = False
  5951. self.source_editor_tab.buttonRun.hide()
  5952. # Switch plot_area to CNCJob tab
  5953. self.ui.plot_tab_area.setCurrentWidget(self.source_editor_tab)
  5954. try:
  5955. self.source_editor_tab.buttonOpen.clicked.disconnect()
  5956. except TypeError:
  5957. pass
  5958. self.source_editor_tab.buttonOpen.clicked.connect(lambda: self.source_editor_tab.handleOpen(filt=flt))
  5959. try:
  5960. self.source_editor_tab.buttonSave.clicked.disconnect()
  5961. except TypeError:
  5962. pass
  5963. self.source_editor_tab.buttonSave.clicked.connect(lambda: self.source_editor_tab.handleSaveGCode(filt=flt))
  5964. # then append the text from GCode to the text editor
  5965. if obj.kind == 'cncjob':
  5966. try:
  5967. file = obj.export_gcode(
  5968. preamble=self.defaults["cncjob_prepend"],
  5969. postamble=self.defaults["cncjob_append"],
  5970. to_file=True)
  5971. if file == 'fail':
  5972. return 'fail'
  5973. except AttributeError:
  5974. self.inform.emit('[WARNING_NOTCL] %s' %
  5975. _("There is no selected object for which to see it's source file code."))
  5976. return 'fail'
  5977. else:
  5978. try:
  5979. file = StringIO(obj.source_file)
  5980. except (AttributeError, TypeError):
  5981. self.inform.emit('[WARNING_NOTCL] %s' %
  5982. _("There is no selected object for which to see it's source file code."))
  5983. return 'fail'
  5984. self.source_editor_tab.t_frame.hide()
  5985. try:
  5986. self.source_editor_tab.code_editor.setPlainText(file.getvalue())
  5987. # for line in file:
  5988. # QtWidgets.QApplication.processEvents()
  5989. # proc_line = str(line).strip('\n')
  5990. # self.source_editor_tab.code_editor.append(proc_line)
  5991. except Exception as e:
  5992. log.debug('App.on_view_source() -->%s' % str(e))
  5993. self.inform.emit('[ERROR] %s: %s' % (_('Failed to load the source code for the selected object'), str(e)))
  5994. return
  5995. self.source_editor_tab.handleTextChanged()
  5996. self.source_editor_tab.t_frame.show()
  5997. self.source_editor_tab.code_editor.moveCursor(QtGui.QTextCursor.Start)
  5998. self.proc_container.view.set_idle()
  5999. # self.ui.show()
  6000. def on_toggle_code_editor(self):
  6001. self.defaults.report_usage("on_toggle_code_editor()")
  6002. if self.toggle_codeeditor is False:
  6003. self.init_code_editor(name=_("Code Editor"))
  6004. self.text_editor_tab.buttonOpen.clicked.disconnect()
  6005. self.text_editor_tab.buttonOpen.clicked.connect(self.text_editor_tab.handleOpen)
  6006. self.text_editor_tab.buttonSave.clicked.disconnect()
  6007. self.text_editor_tab.buttonSave.clicked.connect(self.text_editor_tab.handleSaveGCode)
  6008. else:
  6009. for idx in range(self.ui.plot_tab_area.count()):
  6010. if self.ui.plot_tab_area.widget(idx).objectName() == "text_editor_tab":
  6011. self.ui.plot_tab_area.closeTab(idx)
  6012. break
  6013. self.toggle_codeeditor = False
  6014. def on_code_editor_close(self):
  6015. self.toggle_codeeditor = False
  6016. def goto_text_line(self):
  6017. """
  6018. Will scroll a text to the specified text line.
  6019. :return: None
  6020. """
  6021. dia_box = Dialog_box(title=_("Go to Line ..."),
  6022. label=_("Line:"),
  6023. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  6024. initial_text='')
  6025. try:
  6026. line = int(dia_box.location) - 1
  6027. except (ValueError, TypeError):
  6028. line = 0
  6029. if dia_box.ok:
  6030. # make sure to move first the cursor at the end so after finding the line the line will be positioned
  6031. # at the top of the window
  6032. self.ui.plot_tab_area.currentWidget().code_editor.moveCursor(QTextCursor.End)
  6033. # get the document() of the TextEditor
  6034. doc = self.ui.plot_tab_area.currentWidget().code_editor.document()
  6035. # create a Text Cursor based on the searched line
  6036. cursor = QTextCursor(doc.findBlockByLineNumber(line))
  6037. # set cursor of the code editor with the cursor at the searcehd line
  6038. self.ui.plot_tab_area.currentWidget().code_editor.setTextCursor(cursor)
  6039. def on_filenewscript(self, silent=False):
  6040. """
  6041. Will create a new script file and open it in the Code Editor
  6042. :param silent: if True will not display status messages
  6043. :return: None
  6044. """
  6045. if silent is False:
  6046. self.inform.emit('[success] %s' % _("New TCL script file created in Code Editor."))
  6047. # delete the absolute and relative position and messages in the infobar
  6048. self.ui.position_label.setText("")
  6049. # self.ui.rel_position_label.setText("")
  6050. self.app_obj.new_script_object()
  6051. # script_text = script_obj.source_file
  6052. #
  6053. # self.proc_container.view.set_busy(_("Loading..."))
  6054. # script_obj.script_editor_tab.t_frame.hide()
  6055. #
  6056. # script_obj.script_editor_tab.t_frame.show()
  6057. # self.proc_container.view.set_idle()
  6058. def on_fileopenscript(self, name=None, silent=False):
  6059. """
  6060. Will open a Tcl script file into the Code Editor
  6061. :param silent: if True will not display status messages
  6062. :param name: name of a Tcl script file to open
  6063. :return: None
  6064. """
  6065. self.defaults.report_usage("on_fileopenscript")
  6066. App.log.debug("on_fileopenscript()")
  6067. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6068. "All Files (*.*)"
  6069. if name:
  6070. filenames = [name]
  6071. else:
  6072. try:
  6073. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6074. caption=_("Open TCL script"), directory=self.get_last_folder(), filter=_filter_)
  6075. except TypeError:
  6076. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6077. if len(filenames) == 0:
  6078. if silent is False:
  6079. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6080. else:
  6081. for filename in filenames:
  6082. if filename != '':
  6083. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6084. def on_fileopenscript_example(self, name=None, silent=False):
  6085. """
  6086. Will open a Tcl script file into the Code Editor
  6087. :param silent: if True will not display status messages
  6088. :param name: name of a Tcl script file to open
  6089. :return:
  6090. """
  6091. self.defaults.report_usage("on_fileopenscript_example")
  6092. log.debug("on_fileopenscript_example()")
  6093. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6094. "All Files (*.*)"
  6095. # test if the app was frozen and choose the path for the configuration file
  6096. if getattr(sys, "frozen", False) is True:
  6097. example_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\assets\\examples'
  6098. else:
  6099. example_path = os.path.dirname(os.path.realpath(__file__)) + '\\assets\\examples'
  6100. if name:
  6101. filenames = [name]
  6102. else:
  6103. try:
  6104. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6105. caption=_("Open TCL script"), directory=example_path, filter=_filter_)
  6106. except TypeError:
  6107. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6108. if len(filenames) == 0:
  6109. if silent is False:
  6110. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6111. else:
  6112. for filename in filenames:
  6113. if filename != '':
  6114. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6115. def on_filerunscript(self, name=None, silent=False):
  6116. """
  6117. File menu callback for loading and running a TCL script.
  6118. :param silent: if True will not display status messages
  6119. :param name: name of a Tcl script file to be run by FlatCAM
  6120. :return: None
  6121. """
  6122. self.defaults.report_usage("on_filerunscript")
  6123. App.log.debug("on_file_runscript()")
  6124. if name:
  6125. filename = name
  6126. if self.cmd_line_headless != 1:
  6127. self.splash.showMessage('%s: %ssec\n%s' %
  6128. (_("Canvas initialization started.\n"
  6129. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6130. _("Executing ScriptObject file.")
  6131. ),
  6132. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6133. color=QtGui.QColor("gray"))
  6134. else:
  6135. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6136. "All Files (*.*)"
  6137. try:
  6138. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  6139. directory=self.get_last_folder(), filter=_filter_)
  6140. except TypeError:
  6141. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  6142. # The Qt methods above will return a QString which can cause problems later.
  6143. # So far json.dump() will fail to serialize it.
  6144. filename = str(filename)
  6145. if filename == "":
  6146. if silent is False:
  6147. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6148. else:
  6149. if self.cmd_line_headless != 1:
  6150. if self.ui.shell_dock.isHidden():
  6151. self.ui.shell_dock.show()
  6152. try:
  6153. with open(filename, "r") as tcl_script:
  6154. cmd_line_shellfile_content = tcl_script.read()
  6155. if self.cmd_line_headless != 1:
  6156. self.shell.exec_command(cmd_line_shellfile_content)
  6157. else:
  6158. self.shell.exec_command(cmd_line_shellfile_content, no_echo=True)
  6159. if silent is False:
  6160. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor and executed."))
  6161. except Exception as e:
  6162. log.debug("App.on_filerunscript() -> %s" % str(e))
  6163. sys.exit(2)
  6164. def on_file_saveproject(self, silent=False):
  6165. """
  6166. Callback for menu item File->Save Project. Saves the project to
  6167. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  6168. if set to None. The project is saved by calling ``self.save_project()``.
  6169. :param silent: if True will not display status messages
  6170. :return: None
  6171. """
  6172. self.defaults.report_usage("on_file_saveproject")
  6173. if self.project_filename is None:
  6174. self.on_file_saveprojectas()
  6175. else:
  6176. self.worker_task.emit({'fcn': self.save_project,
  6177. 'params': [self.project_filename, silent]})
  6178. if self.defaults["global_open_style"] is False:
  6179. self.file_opened.emit("project", self.project_filename)
  6180. self.file_saved.emit("project", self.project_filename)
  6181. self.set_ui_title(name=self.project_filename)
  6182. self.should_we_save = False
  6183. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  6184. """
  6185. Callback for menu item File->Save Project As... Opens a file
  6186. chooser and saves the project to the given file via
  6187. ``self.save_project()``.
  6188. :param make_copy if to be create a copy of the project; boolean
  6189. :param use_thread: if to be run in a separate thread; boolean
  6190. :param quit_action: if to be followed by quiting the application; boolean
  6191. :return: None
  6192. """
  6193. self.defaults.report_usage("on_file_saveprojectas")
  6194. self.date = str(datetime.today()).rpartition('.')[0]
  6195. self.date = ''.join(c for c in self.date if c not in ':-')
  6196. self.date = self.date.replace(' ', '_')
  6197. filter_ = "FlatCAM Project .FlatPrj (*.FlatPrj);; All Files (*.*)"
  6198. try:
  6199. filename, _f = FCFileSaveDialog.get_saved_filename(
  6200. caption=_("Save Project As ..."),
  6201. directory='{l_save}/{proj}_{date}'.format(l_save=str(self.get_last_save_folder()), date=self.date,
  6202. proj=_("Project")),
  6203. ext_filter=filter_
  6204. )
  6205. except TypeError:
  6206. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Project As ..."), ext_filter=filter_)
  6207. filename = str(filename)
  6208. if filename == '':
  6209. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6210. return
  6211. if use_thread is True:
  6212. self.worker_task.emit({'fcn': self.save_project,
  6213. 'params': [filename, quit_action]})
  6214. else:
  6215. self.save_project(filename, quit_action)
  6216. # self.save_project(filename)
  6217. if self.defaults["global_open_style"] is False:
  6218. self.file_opened.emit("project", filename)
  6219. self.file_saved.emit("project", filename)
  6220. if not make_copy:
  6221. self.project_filename = filename
  6222. self.set_ui_title(name=self.project_filename)
  6223. self.should_we_save = False
  6224. def on_file_save_objects_pdf(self, use_thread=True):
  6225. self.date = str(datetime.today()).rpartition('.')[0]
  6226. self.date = ''.join(c for c in self.date if c not in ':-')
  6227. self.date = self.date.replace(' ', '_')
  6228. try:
  6229. obj_selection = self.collection.get_selected()
  6230. if len(obj_selection) == 1:
  6231. obj_name = str(obj_selection[0].options['name'])
  6232. else:
  6233. obj_name = _("FlatCAM objects print")
  6234. except AttributeError as err:
  6235. log.debug("App.on_file_save_object_pdf() --> %s" % str(err))
  6236. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  6237. return
  6238. if not obj_selection:
  6239. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  6240. return
  6241. filter_ = "PDF File .pdf (*.PDF);; All Files (*.*)"
  6242. try:
  6243. filename, _f = FCFileSaveDialog.get_saved_filename(
  6244. caption=_("Save Object as PDF ..."),
  6245. directory='{l_save}/{obj_name}_{date}'.format(l_save=str(self.get_last_save_folder()),
  6246. obj_name=obj_name,
  6247. date=self.date),
  6248. ext_filter=filter_
  6249. )
  6250. except TypeError:
  6251. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Object as PDF ..."), ext_filter=filter_)
  6252. filename = str(filename)
  6253. if filename == '':
  6254. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6255. return
  6256. if use_thread is True:
  6257. self.proc_container.new(_("Printing PDF ... Please wait."))
  6258. self.worker_task.emit({'fcn': self.save_pdf, 'params': [filename, obj_selection]})
  6259. else:
  6260. self.save_pdf(filename, obj_selection)
  6261. # self.save_project(filename)
  6262. if self.defaults["global_open_style"] is False:
  6263. self.file_opened.emit("pdf", filename)
  6264. self.file_saved.emit("pdf", filename)
  6265. def save_pdf(self, file_name, obj_selection):
  6266. p_size = self.defaults['global_workspaceT']
  6267. orientation = self.defaults['global_workspace_orientation']
  6268. color = 'black'
  6269. transparency_level = 1.0
  6270. self.pagesize = {}
  6271. self.pagesize.update(
  6272. {
  6273. 'Bounds': None,
  6274. 'A0': (841 * mm, 1189 * mm),
  6275. 'A1': (594 * mm, 841 * mm),
  6276. 'A2': (420 * mm, 594 * mm),
  6277. 'A3': (297 * mm, 420 * mm),
  6278. 'A4': (210 * mm, 297 * mm),
  6279. 'A5': (148 * mm, 210 * mm),
  6280. 'A6': (105 * mm, 148 * mm),
  6281. 'A7': (74 * mm, 105 * mm),
  6282. 'A8': (52 * mm, 74 * mm),
  6283. 'A9': (37 * mm, 52 * mm),
  6284. 'A10': (26 * mm, 37 * mm),
  6285. 'B0': (1000 * mm, 1414 * mm),
  6286. 'B1': (707 * mm, 1000 * mm),
  6287. 'B2': (500 * mm, 707 * mm),
  6288. 'B3': (353 * mm, 500 * mm),
  6289. 'B4': (250 * mm, 353 * mm),
  6290. 'B5': (176 * mm, 250 * mm),
  6291. 'B6': (125 * mm, 176 * mm),
  6292. 'B7': (88 * mm, 125 * mm),
  6293. 'B8': (62 * mm, 88 * mm),
  6294. 'B9': (44 * mm, 62 * mm),
  6295. 'B10': (31 * mm, 44 * mm),
  6296. 'C0': (917 * mm, 1297 * mm),
  6297. 'C1': (648 * mm, 917 * mm),
  6298. 'C2': (458 * mm, 648 * mm),
  6299. 'C3': (324 * mm, 458 * mm),
  6300. 'C4': (229 * mm, 324 * mm),
  6301. 'C5': (162 * mm, 229 * mm),
  6302. 'C6': (114 * mm, 162 * mm),
  6303. 'C7': (81 * mm, 114 * mm),
  6304. 'C8': (57 * mm, 81 * mm),
  6305. 'C9': (40 * mm, 57 * mm),
  6306. 'C10': (28 * mm, 40 * mm),
  6307. # American paper sizes
  6308. 'LETTER': (8.5 * inch, 11 * inch),
  6309. 'LEGAL': (8.5 * inch, 14 * inch),
  6310. 'ELEVENSEVENTEEN': (11 * inch, 17 * inch),
  6311. # From https://en.wikipedia.org/wiki/Paper_size
  6312. 'JUNIOR_LEGAL': (5 * inch, 8 * inch),
  6313. 'HALF_LETTER': (5.5 * inch, 8 * inch),
  6314. 'GOV_LETTER': (8 * inch, 10.5 * inch),
  6315. 'GOV_LEGAL': (8.5 * inch, 13 * inch),
  6316. 'LEDGER': (17 * inch, 11 * inch),
  6317. }
  6318. )
  6319. exported_svg = []
  6320. for obj in obj_selection:
  6321. svg_obj = obj.export_svg(scale_stroke_factor=0.0,
  6322. scale_factor_x=None, scale_factor_y=None,
  6323. skew_factor_x=None, skew_factor_y=None,
  6324. mirror=None)
  6325. if obj.kind.lower() == 'gerber':
  6326. # color = self.defaults["gerber_plot_fill"][:-2]
  6327. color = obj.fill_color[:-2]
  6328. elif obj.kind.lower() == 'excellon':
  6329. color = '#C40000'
  6330. elif obj.kind.lower() == 'geometry':
  6331. color = self.defaults["global_draw_color"]
  6332. # Change the attributes of the exported SVG
  6333. # We don't need stroke-width
  6334. # We set opacity to maximum
  6335. # We set the colour to WHITE
  6336. root = ET.fromstring(svg_obj)
  6337. for child in root:
  6338. child.set('fill', str(color))
  6339. child.set('opacity', str(transparency_level))
  6340. child.set('stroke', str(color))
  6341. exported_svg.append(ET.tostring(root))
  6342. xmin = Inf
  6343. ymin = Inf
  6344. xmax = -Inf
  6345. ymax = -Inf
  6346. for obj in obj_selection:
  6347. try:
  6348. gxmin, gymin, gxmax, gymax = obj.bounds()
  6349. xmin = min([xmin, gxmin])
  6350. ymin = min([ymin, gymin])
  6351. xmax = max([xmax, gxmax])
  6352. ymax = max([ymax, gymax])
  6353. except Exception as e:
  6354. log.warning("DEV WARNING: Tried to get bounds of empty geometry in App.save_pdf(). %s" % str(e))
  6355. # Determine bounding area for svg export
  6356. bounds = [xmin, ymin, xmax, ymax]
  6357. size = bounds[2] - bounds[0], bounds[3] - bounds[1]
  6358. # This contain the measure units
  6359. uom = obj_selection[0].units.lower()
  6360. # Define a boundary around SVG of about 1.0mm (~39mils)
  6361. if uom in "mm":
  6362. boundary = 1.0
  6363. else:
  6364. boundary = 0.0393701
  6365. # Convert everything to strings for use in the xml doc
  6366. svgwidth = str(size[0] + (2 * boundary))
  6367. svgheight = str(size[1] + (2 * boundary))
  6368. minx = str(bounds[0] - boundary)
  6369. miny = str(bounds[1] + boundary + size[1])
  6370. # Add a SVG Header and footer to the svg output from shapely
  6371. # The transform flips the Y Axis so that everything renders
  6372. # properly within svg apps such as inkscape
  6373. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  6374. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  6375. svg_header += 'width="' + svgwidth + uom + '" '
  6376. svg_header += 'height="' + svgheight + uom + '" '
  6377. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  6378. svg_header += '>'
  6379. svg_header += '<g transform="scale(1,-1)">'
  6380. svg_footer = '</g> </svg>'
  6381. svg_elem = str(svg_header)
  6382. for svg_item in exported_svg:
  6383. svg_elem += str(svg_item)
  6384. svg_elem += str(svg_footer)
  6385. # Parse the xml through a xml parser just to add line feeds
  6386. # and to make it look more pretty for the output
  6387. doc = parse_xml_string(svg_elem)
  6388. doc_final = doc.toprettyxml()
  6389. try:
  6390. if self.defaults['units'].upper() == 'IN':
  6391. unit = inch
  6392. else:
  6393. unit = mm
  6394. doc_final = StringIO(doc_final)
  6395. drawing = svg2rlg(doc_final)
  6396. if p_size == 'Bounds':
  6397. renderPDF.drawToFile(drawing, file_name)
  6398. else:
  6399. if orientation == 'p':
  6400. page_size = portrait(self.pagesize[p_size])
  6401. else:
  6402. page_size = landscape(self.pagesize[p_size])
  6403. my_canvas = canvas.Canvas(file_name, pagesize=page_size)
  6404. my_canvas.translate(bounds[0] * unit, bounds[1] * unit)
  6405. renderPDF.draw(drawing, my_canvas, 0, 0)
  6406. my_canvas.save()
  6407. except Exception as e:
  6408. log.debug("App.save_pdf() --> PDF output --> %s" % str(e))
  6409. return 'fail'
  6410. self.inform.emit('[success] %s: %s' % (_("PDF file saved to"), file_name))
  6411. def export_svg(self, obj_name, filename, scale_stroke_factor=0.00):
  6412. """
  6413. Exports a Geometry Object to an SVG file.
  6414. :param obj_name: the name of the FlatCAM object to be saved as SVG
  6415. :param filename: Path to the SVG file to save to.
  6416. :param scale_stroke_factor: factor by which to change/scale the thickness of the features
  6417. :return:
  6418. """
  6419. self.defaults.report_usage("export_svg()")
  6420. if filename is None:
  6421. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6422. is not None else self.defaults["global_last_folder"]
  6423. self.log.debug("export_svg()")
  6424. try:
  6425. obj = self.collection.get_by_name(str(obj_name))
  6426. except Exception:
  6427. # TODO: The return behavior has not been established... should raise exception?
  6428. return "Could not retrieve object: %s" % obj_name
  6429. with self.proc_container.new(_("Exporting SVG")) as proc:
  6430. exported_svg = obj.export_svg(scale_stroke_factor=scale_stroke_factor)
  6431. # Determine bounding area for svg export
  6432. bounds = obj.bounds()
  6433. size = obj.size()
  6434. # Convert everything to strings for use in the xml doc
  6435. svgwidth = str(size[0])
  6436. svgheight = str(size[1])
  6437. minx = str(bounds[0])
  6438. miny = str(bounds[1] - size[1])
  6439. uom = obj.units.lower()
  6440. # Add a SVG Header and footer to the svg output from shapely
  6441. # The transform flips the Y Axis so that everything renders
  6442. # properly within svg apps such as inkscape
  6443. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  6444. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  6445. svg_header += 'width="' + svgwidth + uom + '" '
  6446. svg_header += 'height="' + svgheight + uom + '" '
  6447. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  6448. svg_header += '<g transform="scale(1,-1)">'
  6449. svg_footer = '</g> </svg>'
  6450. svg_elem = svg_header + exported_svg + svg_footer
  6451. # Parse the xml through a xml parser just to add line feeds
  6452. # and to make it look more pretty for the output
  6453. svgcode = parse_xml_string(svg_elem)
  6454. svgcode = svgcode.toprettyxml()
  6455. try:
  6456. with open(filename, 'w') as fp:
  6457. fp.write(svgcode)
  6458. except PermissionError:
  6459. self.inform.emit('[WARNING] %s' %
  6460. _("Permission denied, saving not possible.\n"
  6461. "Most likely another app is holding the file open and not accessible."))
  6462. return 'fail'
  6463. if self.defaults["global_open_style"] is False:
  6464. self.file_opened.emit("SVG", filename)
  6465. self.file_saved.emit("SVG", filename)
  6466. self.inform.emit('[success] %s: %s' % (_("SVG file exported to"), filename))
  6467. def save_source_file(self, obj_name, filename, use_thread=True):
  6468. """
  6469. Exports a FlatCAM Object to an Gerber/Excellon file.
  6470. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  6471. :param filename: Path to the Gerber file to save to.
  6472. :param use_thread: if to be run in a separate thread
  6473. :return:
  6474. """
  6475. self.defaults.report_usage("save source file()")
  6476. if filename is None:
  6477. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6478. is not None else self.defaults["global_last_folder"]
  6479. self.log.debug("save source file()")
  6480. obj = self.collection.get_by_name(obj_name)
  6481. file_string = StringIO(obj.source_file)
  6482. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  6483. if file_string.getvalue() == '':
  6484. self.inform.emit('[ERROR_NOTCL] %s' %
  6485. _("Save cancelled because source file is empty. Try to export the Gerber file."))
  6486. return 'fail'
  6487. try:
  6488. with open(filename, 'w') as file:
  6489. file.writelines('G04*\n')
  6490. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  6491. (obj.kind.upper(), str(self.version), str(self.version_date)))
  6492. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  6493. file.writelines('G04 Created on : %s*\n' % time_string)
  6494. for line in file_string:
  6495. file.writelines(line)
  6496. except PermissionError:
  6497. self.inform.emit('[WARNING] %s' %
  6498. _("Permission denied, saving not possible.\n"
  6499. "Most likely another app is holding the file open and not accessible."))
  6500. return 'fail'
  6501. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  6502. """
  6503. Exports a Excellon Object to an Excellon file.
  6504. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  6505. :param filename: Path to the Excellon file to save to.
  6506. :param local_use:
  6507. :param use_thread: if to be run in a separate thread
  6508. :return:
  6509. """
  6510. self.defaults.report_usage("export_excellon()")
  6511. if filename is None:
  6512. if self.defaults["global_last_save_folder"]:
  6513. filename = self.defaults["global_last_save_folder"] + '/' + 'exported_excellon'
  6514. else:
  6515. filename = self.defaults["global_last_folder"] + '/' + 'exported_excellon'
  6516. self.log.debug("export_excellon()")
  6517. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  6518. self.defaults["excellon_exp_decimals"]
  6519. )
  6520. if local_use is None:
  6521. try:
  6522. obj = self.collection.get_by_name(str(obj_name))
  6523. except Exception:
  6524. return "Could not retrieve object: %s" % obj_name
  6525. else:
  6526. obj = local_use
  6527. if not isinstance(obj, ExcellonObject):
  6528. self.inform.emit('[ERROR_NOTCL] %s' %
  6529. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6530. return
  6531. # updated units
  6532. eunits = self.defaults["excellon_exp_units"]
  6533. ewhole = self.defaults["excellon_exp_integer"]
  6534. efract = self.defaults["excellon_exp_decimals"]
  6535. ezeros = self.defaults["excellon_exp_zeros"]
  6536. eformat = self.defaults["excellon_exp_format"]
  6537. slot_type = self.defaults["excellon_exp_slot_type"]
  6538. fc_units = self.defaults['units'].upper()
  6539. if fc_units == 'MM':
  6540. factor = 1 if eunits == 'METRIC' else 0.03937
  6541. else:
  6542. factor = 25.4 if eunits == 'METRIC' else 1
  6543. def make_excellon():
  6544. try:
  6545. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  6546. header = 'M48\n'
  6547. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  6548. (str(self.version), str(self.version_date))
  6549. header += ';Filename: %s' % str(obj_name) + '\n'
  6550. header += ';Created on : %s' % time_str + '\n'
  6551. if eformat == 'dec':
  6552. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  6553. header += eunits + '\n'
  6554. for tool in obj.tools:
  6555. if eunits == 'METRIC':
  6556. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6557. tool=str(tool),
  6558. dec=2)
  6559. else:
  6560. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6561. tool=str(tool),
  6562. dec=4)
  6563. else:
  6564. if ezeros == 'LZ':
  6565. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  6566. form='ndec', e_zeros='LZ', factor=factor,
  6567. slot_type=slot_type)
  6568. header += '%s,%s\n' % (eunits, 'LZ')
  6569. header += format_exc
  6570. for tool in obj.tools:
  6571. if eunits == 'METRIC':
  6572. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6573. tool=str(tool),
  6574. dec=2)
  6575. else:
  6576. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6577. tool=str(tool),
  6578. dec=4)
  6579. else:
  6580. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  6581. form='ndec', e_zeros='TZ', factor=factor,
  6582. slot_type=slot_type)
  6583. header += '%s,%s\n' % (eunits, 'TZ')
  6584. header += format_exc
  6585. for tool in obj.tools:
  6586. if eunits == 'METRIC':
  6587. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6588. tool=str(tool),
  6589. dec=2)
  6590. else:
  6591. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6592. tool=str(tool),
  6593. dec=4)
  6594. header += '%\n'
  6595. footer = 'M30\n'
  6596. exported_excellon = header
  6597. exported_excellon += excellon_code
  6598. exported_excellon += footer
  6599. if local_use is None:
  6600. try:
  6601. with open(filename, 'w') as fp:
  6602. fp.write(exported_excellon)
  6603. except PermissionError:
  6604. self.inform.emit('[WARNING] %s' %
  6605. _("Permission denied, saving not possible.\n"
  6606. "Most likely another app is holding the file open and not accessible."))
  6607. return 'fail'
  6608. if self.defaults["global_open_style"] is False:
  6609. self.file_opened.emit("Excellon", filename)
  6610. self.file_saved.emit("Excellon", filename)
  6611. self.inform.emit('[success] %s: %s' % (_("Excellon file exported to"), filename))
  6612. else:
  6613. return exported_excellon
  6614. except Exception as e:
  6615. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  6616. return 'fail'
  6617. if use_thread is True:
  6618. with self.proc_container.new(_("Exporting Excellon")) as proc:
  6619. def job_thread_exc(app_obj):
  6620. ret = make_excellon()
  6621. if ret == 'fail':
  6622. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  6623. return
  6624. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  6625. else:
  6626. eret = make_excellon()
  6627. if eret == 'fail':
  6628. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  6629. return 'fail'
  6630. if local_use is not None:
  6631. return eret
  6632. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  6633. """
  6634. Exports a Gerber Object to an Gerber file.
  6635. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  6636. :param filename: Path to the Gerber file to save to.
  6637. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  6638. When not None, the value will be the actual Gerber object for which to create the Gerber code
  6639. :param use_thread: if to be run in a separate thread
  6640. :return:
  6641. """
  6642. self.defaults.report_usage("export_gerber()")
  6643. if filename is None:
  6644. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6645. is not None else self.defaults["global_last_folder"]
  6646. self.log.debug("export_gerber()")
  6647. if local_use is None:
  6648. try:
  6649. obj = self.collection.get_by_name(str(obj_name))
  6650. except Exception:
  6651. return "Could not retrieve object: %s" % obj_name
  6652. else:
  6653. obj = local_use
  6654. # updated units
  6655. gunits = self.defaults["gerber_exp_units"]
  6656. gwhole = self.defaults["gerber_exp_integer"]
  6657. gfract = self.defaults["gerber_exp_decimals"]
  6658. gzeros = self.defaults["gerber_exp_zeros"]
  6659. fc_units = self.defaults['units'].upper()
  6660. if fc_units == 'MM':
  6661. factor = 1 if gunits == 'MM' else 0.03937
  6662. else:
  6663. factor = 25.4 if gunits == 'MM' else 1
  6664. def make_gerber():
  6665. try:
  6666. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  6667. header = 'G04*\n'
  6668. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  6669. (str(self.version), str(self.version_date))
  6670. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  6671. header += 'G04 Created on : %s*' % time_str + '\n'
  6672. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  6673. header += "%MO{units}*%\n".format(units=gunits)
  6674. for apid in obj.apertures:
  6675. if obj.apertures[apid]['type'] == 'C':
  6676. header += "%ADD{apid}{type},{size}*%\n".format(
  6677. apid=str(apid),
  6678. type='C',
  6679. size=(factor * obj.apertures[apid]['size'])
  6680. )
  6681. elif obj.apertures[apid]['type'] == 'R':
  6682. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  6683. apid=str(apid),
  6684. type='R',
  6685. width=(factor * obj.apertures[apid]['width']),
  6686. height=(factor * obj.apertures[apid]['height'])
  6687. )
  6688. elif obj.apertures[apid]['type'] == 'O':
  6689. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  6690. apid=str(apid),
  6691. type='O',
  6692. width=(factor * obj.apertures[apid]['width']),
  6693. height=(factor * obj.apertures[apid]['height'])
  6694. )
  6695. header += '\n'
  6696. # obsolete units but some software may need it
  6697. if gunits == 'IN':
  6698. header += 'G70*\n'
  6699. else:
  6700. header += 'G71*\n'
  6701. # Absolute Mode
  6702. header += 'G90*\n'
  6703. header += 'G01*\n'
  6704. # positive polarity
  6705. header += '%LPD*%\n'
  6706. footer = 'M02*\n'
  6707. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  6708. exported_gerber = header
  6709. exported_gerber += gerber_code
  6710. exported_gerber += footer
  6711. if local_use is None:
  6712. try:
  6713. with open(filename, 'w') as fp:
  6714. fp.write(exported_gerber)
  6715. except PermissionError:
  6716. self.inform.emit('[WARNING] %s' %
  6717. _("Permission denied, saving not possible.\n"
  6718. "Most likely another app is holding the file open and not accessible."))
  6719. return 'fail'
  6720. if self.defaults["global_open_style"] is False:
  6721. self.file_opened.emit("Gerber", filename)
  6722. self.file_saved.emit("Gerber", filename)
  6723. self.inform.emit('[success] %s: %s' % (_("Gerber file exported to"), filename))
  6724. else:
  6725. return exported_gerber
  6726. except Exception as e:
  6727. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  6728. return 'fail'
  6729. if use_thread is True:
  6730. with self.proc_container.new(_("Exporting Gerber")) as proc:
  6731. def job_thread_grb(app_obj):
  6732. ret = make_gerber()
  6733. if ret == 'fail':
  6734. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  6735. return
  6736. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  6737. else:
  6738. gret = make_gerber()
  6739. if gret == 'fail':
  6740. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  6741. return 'fail'
  6742. if local_use is not None:
  6743. return gret
  6744. def export_dxf(self, obj_name, filename, use_thread=True):
  6745. """
  6746. Exports a Geometry Object to an DXF file.
  6747. :param obj_name: the name of the FlatCAM object to be saved as DXF
  6748. :param filename: Path to the DXF file to save to.
  6749. :param use_thread: if to be run in a separate thread
  6750. :return:
  6751. """
  6752. self.defaults.report_usage("export_dxf()")
  6753. if filename is None:
  6754. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6755. is not None else self.defaults["global_last_folder"]
  6756. self.log.debug("export_dxf()")
  6757. try:
  6758. obj = self.collection.get_by_name(str(obj_name))
  6759. except Exception:
  6760. # TODO: The return behavior has not been established... should raise exception?
  6761. return "Could not retrieve object: %s" % obj_name
  6762. def make_dxf():
  6763. try:
  6764. dxf_code = obj.export_dxf()
  6765. dxf_code.saveas(filename)
  6766. if self.defaults["global_open_style"] is False:
  6767. self.file_opened.emit("DXF", filename)
  6768. self.file_saved.emit("DXF", filename)
  6769. self.inform.emit('[success] %s: %s' % (_("DXF file exported to"), filename))
  6770. except Exception:
  6771. return 'fail'
  6772. if use_thread is True:
  6773. with self.proc_container.new(_("Exporting DXF")) as proc:
  6774. def job_thread_exc(app_obj):
  6775. ret_dxf_val = make_dxf()
  6776. if ret_dxf_val == 'fail':
  6777. app_obj.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  6778. return
  6779. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  6780. else:
  6781. ret = make_dxf()
  6782. if ret == 'fail':
  6783. self.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  6784. return
  6785. def import_svg(self, filename, geo_type='geometry', outname=None, plot=True):
  6786. """
  6787. Adds a new Geometry Object to the projects and populates
  6788. it with shapes extracted from the SVG file.
  6789. :param plot: If True then the resulting object will be plotted on canvas
  6790. :param filename: Path to the SVG file.
  6791. :param geo_type: Type of FlatCAM object that will be created from SVG
  6792. :param outname: The name given to the resulting FlatCAM object
  6793. :return:
  6794. """
  6795. self.defaults.report_usage("import_svg()")
  6796. log.debug("App.import_svg()")
  6797. obj_type = ""
  6798. if geo_type is None or geo_type == "geometry":
  6799. obj_type = "geometry"
  6800. elif geo_type == "gerber":
  6801. obj_type = "gerber"
  6802. else:
  6803. self.inform.emit('[ERROR_NOTCL] %s' %
  6804. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  6805. return
  6806. units = self.defaults['units'].upper()
  6807. def obj_init(geo_obj, app_obj):
  6808. geo_obj.import_svg(filename, obj_type, units=units)
  6809. geo_obj.multigeo = False
  6810. geo_obj.source_file = self.export_gerber(obj_name=name, filename=None, local_use=geo_obj, use_thread=False)
  6811. with self.proc_container.new(_("Importing SVG")) as proc:
  6812. # Object name
  6813. name = outname or filename.split('/')[-1].split('\\')[-1]
  6814. ret = self.app_obj.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  6815. if ret == 'fail':
  6816. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  6817. return 'fail'
  6818. # Register recent file
  6819. self.file_opened.emit("svg", filename)
  6820. # AppGUI feedback
  6821. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  6822. def import_dxf(self, filename, geo_type='geometry', outname=None, plot=True):
  6823. """
  6824. Adds a new Geometry Object to the projects and populates
  6825. it with shapes extracted from the DXF file.
  6826. :param filename: Path to the DXF file.
  6827. :param geo_type: Type of FlatCAM object that will be created from DXF
  6828. :param outname: Name for the imported Geometry
  6829. :param plot: If True then the resulting object will be plotted on canvas
  6830. :return:
  6831. """
  6832. self.defaults.report_usage("import_dxf()")
  6833. obj_type = ""
  6834. if geo_type is None or geo_type == "geometry":
  6835. obj_type = "geometry"
  6836. elif geo_type == "gerber":
  6837. obj_type = geo_type
  6838. else:
  6839. self.inform.emit('[ERROR_NOTCL] %s' %
  6840. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  6841. return
  6842. units = self.defaults['units'].upper()
  6843. def obj_init(geo_obj, app_obj):
  6844. geo_obj.import_dxf(filename, obj_type, units=units)
  6845. geo_obj.multigeo = False
  6846. with self.proc_container.new(_("Importing DXF")):
  6847. # Object name
  6848. name = outname or filename.split('/')[-1].split('\\')[-1]
  6849. ret = self.app_obj.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  6850. if ret == 'fail':
  6851. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  6852. return 'fail'
  6853. # Register recent file
  6854. self.file_opened.emit("dxf", filename)
  6855. # AppGUI feedback
  6856. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  6857. def open_gerber(self, filename, outname=None, plot=True, from_tcl=False):
  6858. """
  6859. Opens a Gerber file, parses it and creates a new object for
  6860. it in the program. Thread-safe.
  6861. :param outname: Name of the resulting object. None causes the
  6862. name to be that of the file. Str.
  6863. :param filename: Gerber file filename
  6864. :type filename: str
  6865. :param plot: boolean, to plot or not the resulting object
  6866. :param from_tcl: True if run from Tcl Shell
  6867. :return: None
  6868. """
  6869. # How the object should be initialized
  6870. def obj_init(gerber_obj, app_obj):
  6871. assert isinstance(gerber_obj, GerberObject), \
  6872. "Expected to initialize a GerberObject but got %s" % type(gerber_obj)
  6873. # Opening the file happens here
  6874. try:
  6875. gerber_obj.parse_file(filename)
  6876. except IOError:
  6877. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  6878. return "fail"
  6879. except ParseError as err:
  6880. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  6881. app_obj.log.error(str(err))
  6882. return "fail"
  6883. except Exception as e:
  6884. log.debug("App.open_gerber() --> %s" % str(e))
  6885. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  6886. msg += traceback.format_exc()
  6887. app_obj.inform.emit(msg)
  6888. return "fail"
  6889. if gerber_obj.is_empty():
  6890. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  6891. _("Object is not Gerber file or empty. Aborting object creation."))
  6892. return "fail"
  6893. App.log.debug("open_gerber()")
  6894. with self.proc_container.new(_("Opening Gerber")):
  6895. # Object name
  6896. name = outname or filename.split('/')[-1].split('\\')[-1]
  6897. # # ## Object creation # ##
  6898. ret_val = self.app_obj.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  6899. if ret_val == 'fail':
  6900. if from_tcl:
  6901. filename = self.defaults['global_tcl_path'] + '/' + name
  6902. ret_val = self.app_obj.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  6903. if ret_val == 'fail':
  6904. self.inform.emit('[ERROR_NOTCL]%s' % _('Open Gerber failed. Probable not a Gerber file.'))
  6905. return 'fail'
  6906. # Register recent file
  6907. self.file_opened.emit("gerber", filename)
  6908. # AppGUI feedback
  6909. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  6910. def open_excellon(self, filename, outname=None, plot=True, from_tcl=False):
  6911. """
  6912. Opens an Excellon file, parses it and creates a new object for
  6913. it in the program. Thread-safe.
  6914. :param outname: Name of the resulting object. None causes the name to be that of the file.
  6915. :param filename: Excellon file filename
  6916. :type filename: str
  6917. :param plot: boolean, to plot or not the resulting object
  6918. :param from_tcl: True if run from Tcl Shell
  6919. :return: None
  6920. """
  6921. App.log.debug("open_excellon()")
  6922. # How the object should be initialized
  6923. def obj_init(excellon_obj, app_obj):
  6924. try:
  6925. ret = excellon_obj.parse_file(filename=filename)
  6926. if ret == "fail":
  6927. log.debug("Excellon parsing failed.")
  6928. self.inform.emit('[ERROR_NOTCL] %s' %
  6929. _("This is not Excellon file."))
  6930. return "fail"
  6931. except IOError:
  6932. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  6933. (_("Cannot open file"), filename))
  6934. log.debug("Could not open Excellon object.")
  6935. return "fail"
  6936. except Exception:
  6937. msg = '[ERROR_NOTCL] %s' % \
  6938. _("An internal error has occurred. See shell.\n")
  6939. msg += traceback.format_exc()
  6940. app_obj.inform.emit(msg)
  6941. return "fail"
  6942. ret = excellon_obj.create_geometry()
  6943. if ret == 'fail':
  6944. log.debug("Could not create geometry for Excellon object.")
  6945. return "fail"
  6946. for tool in excellon_obj.tools:
  6947. if excellon_obj.tools[tool]['solid_geometry']:
  6948. return
  6949. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("No geometry found in file"), filename))
  6950. return "fail"
  6951. with self.proc_container.new(_("Opening Excellon.")):
  6952. # Object name
  6953. name = outname or filename.split('/')[-1].split('\\')[-1]
  6954. ret_val = self.app_obj.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  6955. if ret_val == 'fail':
  6956. if from_tcl:
  6957. filename = self.defaults['global_tcl_path'] + '/' + name
  6958. ret_val = self.app_obj.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  6959. if ret_val == 'fail':
  6960. self.inform.emit('[ERROR_NOTCL] %s' %
  6961. _('Open Excellon file failed. Probable not an Excellon file.'))
  6962. return
  6963. # Register recent file
  6964. self.file_opened.emit("excellon", filename)
  6965. # AppGUI feedback
  6966. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  6967. def open_gcode(self, filename, outname=None, force_parsing=None, plot=True, from_tcl=False):
  6968. """
  6969. Opens a G-gcode file, parses it and creates a new object for
  6970. it in the program. Thread-safe.
  6971. :param filename: G-code file filename
  6972. :param outname: Name of the resulting object. None causes the name to be that of the file.
  6973. :param force_parsing:
  6974. :param plot: If True plot the object on canvas
  6975. :param from_tcl: True if run from Tcl Shell
  6976. :return: None
  6977. """
  6978. App.log.debug("open_gcode()")
  6979. # How the object should be initialized
  6980. def obj_init(job_obj, app_obj_):
  6981. """
  6982. :param job_obj: the resulting object
  6983. :type app_obj_: App
  6984. """
  6985. assert isinstance(app_obj_, App), \
  6986. "Initializer expected App, got %s" % type(app_obj_)
  6987. app_obj_.inform.emit('%s...' % _("Reading GCode file"))
  6988. try:
  6989. f = open(filename)
  6990. gcode = f.read()
  6991. f.close()
  6992. except IOError:
  6993. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open"), filename))
  6994. return "fail"
  6995. job_obj.gcode = gcode
  6996. gcode_ret = job_obj.gcode_parse(force_parsing=force_parsing)
  6997. if gcode_ret == "fail":
  6998. self.inform.emit('[ERROR_NOTCL] %s' % _("This is not GCODE"))
  6999. return "fail"
  7000. job_obj.create_geometry()
  7001. with self.proc_container.new(_("Opening G-Code.")):
  7002. # Object name
  7003. name = outname or filename.split('/')[-1].split('\\')[-1]
  7004. # New object creation and file processing
  7005. ret_val = self.app_obj.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  7006. if ret_val == 'fail':
  7007. if from_tcl:
  7008. filename = self.defaults['global_tcl_path'] + '/' + name
  7009. ret_val = self.app_obj.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  7010. if ret_val == 'fail':
  7011. self.inform.emit('[ERROR_NOTCL] %s' %
  7012. _("Failed to create CNCJob Object. Probable not a GCode file. "
  7013. "Try to load it from File menu.\n "
  7014. "Attempting to create a FlatCAM CNCJob Object from "
  7015. "G-Code file failed during processing"))
  7016. return "fail"
  7017. # Register recent file
  7018. self.file_opened.emit("cncjob", filename)
  7019. # AppGUI feedback
  7020. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7021. def open_hpgl2(self, filename, outname=None):
  7022. """
  7023. Opens a HPGL2 file, parses it and creates a new object for
  7024. it in the program. Thread-safe.
  7025. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7026. :param filename: HPGL2 file filename
  7027. :return: None
  7028. """
  7029. filename = filename
  7030. # How the object should be initialized
  7031. def obj_init(geo_obj, app_obj):
  7032. assert isinstance(geo_obj, GeometryObject), \
  7033. "Expected to initialize a GeometryObject but got %s" % type(geo_obj)
  7034. # Opening the file happens here
  7035. obj = HPGL2(self)
  7036. try:
  7037. HPGL2.parse_file(obj, filename)
  7038. except IOError:
  7039. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7040. return "fail"
  7041. except ParseError as err:
  7042. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7043. app_obj.log.error(str(err))
  7044. return "fail"
  7045. except Exception as e:
  7046. log.debug("App.open_hpgl2() --> %s" % str(e))
  7047. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7048. msg += traceback.format_exc()
  7049. app_obj.inform.emit(msg)
  7050. return "fail"
  7051. geo_obj.multigeo = True
  7052. geo_obj.solid_geometry = deepcopy(obj.solid_geometry)
  7053. geo_obj.tools = deepcopy(obj.tools)
  7054. geo_obj.source_file = deepcopy(obj.source_file)
  7055. del obj
  7056. if not geo_obj.solid_geometry:
  7057. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  7058. _("Object is not HPGL2 file or empty. Aborting object creation."))
  7059. return "fail"
  7060. App.log.debug("open_hpgl2()")
  7061. with self.proc_container.new(_("Opening HPGL2")):
  7062. # Object name
  7063. name = outname or filename.split('/')[-1].split('\\')[-1]
  7064. # # ## Object creation # ##
  7065. ret = self.app_obj.new_object("geometry", name, obj_init, autoselected=False)
  7066. if ret == 'fail':
  7067. self.inform.emit('[ERROR_NOTCL]%s' % _(' Open HPGL2 failed. Probable not a HPGL2 file.'))
  7068. return 'fail'
  7069. # Register recent file
  7070. self.file_opened.emit("geometry", filename)
  7071. # AppGUI feedback
  7072. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7073. def open_script(self, filename, outname=None, silent=False):
  7074. """
  7075. Opens a Script file, parses it and creates a new object for
  7076. it in the program. Thread-safe.
  7077. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7078. :param filename: Script file filename
  7079. :param silent: If True there will be no messages printed to StatusBar
  7080. :return: None
  7081. """
  7082. def obj_init(script_obj, app_obj):
  7083. assert isinstance(script_obj, ScriptObject), \
  7084. "Expected to initialize a ScriptObject but got %s" % type(script_obj)
  7085. if silent is False:
  7086. app_obj.inform.emit('[success] %s' % _("TCL script file opened in Code Editor."))
  7087. try:
  7088. script_obj.parse_file(filename)
  7089. except IOError:
  7090. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7091. return "fail"
  7092. except ParseError as err:
  7093. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7094. app_obj.log.error(str(err))
  7095. return "fail"
  7096. except Exception as e:
  7097. log.debug("App.open_script() -> %s" % str(e))
  7098. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7099. msg += traceback.format_exc()
  7100. app_obj.inform.emit(msg)
  7101. return "fail"
  7102. App.log.debug("open_script()")
  7103. with self.proc_container.new(_("Opening TCL Script...")):
  7104. # Object name
  7105. script_name = outname or filename.split('/')[-1].split('\\')[-1]
  7106. # Object creation
  7107. ret_val = self.app_obj.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  7108. if ret_val == 'fail':
  7109. filename = self.defaults['global_tcl_path'] + '/' + script_name
  7110. ret_val = self.app_obj.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  7111. if ret_val == 'fail':
  7112. self.inform.emit('[ERROR_NOTCL]%s' % _('Failed to open TCL Script.'))
  7113. return 'fail'
  7114. # Register recent file
  7115. self.file_opened.emit("script", filename)
  7116. # AppGUI feedback
  7117. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7118. def open_config_file(self, filename, run_from_arg=None):
  7119. """
  7120. Loads a config file from the specified file.
  7121. :param filename: Name of the file from which to load.
  7122. :param run_from_arg: if True the FlatConfig file will be open as an command line argument
  7123. :return: None
  7124. """
  7125. App.log.debug("Opening config file: " + filename)
  7126. if run_from_arg:
  7127. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7128. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7129. _("Opening FlatCAM Config file.")),
  7130. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7131. color=QtGui.QColor("gray"))
  7132. # # add the tab if it was closed
  7133. # self.ui.plot_tab_area.addTab(self.ui.text_editor_tab, _("Code Editor"))
  7134. # # first clear previous text in text editor (if any)
  7135. # self.ui.text_editor_tab.code_editor.clear()
  7136. #
  7137. # # Switch plot_area to CNCJob tab
  7138. # self.ui.plot_tab_area.setCurrentWidget(self.ui.text_editor_tab)
  7139. # close the Code editor if already open
  7140. if self.toggle_codeeditor:
  7141. self.on_toggle_code_editor()
  7142. self.on_toggle_code_editor()
  7143. try:
  7144. if filename:
  7145. f = QtCore.QFile(filename)
  7146. if f.open(QtCore.QIODevice.ReadOnly):
  7147. stream = QtCore.QTextStream(f)
  7148. code_edited = stream.readAll()
  7149. self.text_editor_tab.code_editor.setPlainText(code_edited)
  7150. f.close()
  7151. except IOError:
  7152. App.log.error("Failed to open config file: %s" % filename)
  7153. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  7154. (_("Failed to open config file"), filename))
  7155. return
  7156. def open_project(self, filename, run_from_arg=None, plot=True, cli=None, from_tcl=False):
  7157. """
  7158. Loads a project from the specified file.
  7159. 1) Loads and parses file
  7160. 2) Registers the file as recently opened.
  7161. 3) Calls on_file_new()
  7162. 4) Updates options
  7163. 5) Calls app_obj.new_object() with the object's from_dict() as init method.
  7164. 6) Calls plot_all() if plot=True
  7165. :param filename: Name of the file from which to load.
  7166. :param run_from_arg: True if run for arguments
  7167. :param plot: If True plot all objects in the project
  7168. :param cli: Run from command line
  7169. :param from_tcl: True if run from Tcl Sehll
  7170. :return: None
  7171. """
  7172. App.log.debug("Opening project: " + filename)
  7173. # block autosaving while a project is loaded
  7174. self.block_autosave = True
  7175. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7176. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7177. if cli is None:
  7178. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  7179. if run_from_arg:
  7180. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7181. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7182. _("Opening FlatCAM Project file.")),
  7183. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7184. color=QtGui.QColor("gray"))
  7185. # Open and parse an uncompressed Project file
  7186. try:
  7187. f = open(filename, 'r')
  7188. except IOError:
  7189. if from_tcl:
  7190. name = filename.split('/')[-1].split('\\')[-1]
  7191. filename = self.defaults['global_tcl_path'] + '/' + name
  7192. try:
  7193. f = open(filename, 'r')
  7194. except IOError:
  7195. log.error("Failed to open project file: %s" % filename)
  7196. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7197. return
  7198. else:
  7199. log.error("Failed to open project file: %s" % filename)
  7200. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7201. return
  7202. try:
  7203. d = json.load(f, object_hook=dict2obj)
  7204. except Exception as e:
  7205. log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  7206. (filename, str(e)))
  7207. f.close()
  7208. # Open and parse a compressed Project file
  7209. try:
  7210. with lzma.open(filename) as f:
  7211. file_content = f.read().decode('utf-8')
  7212. d = json.loads(file_content, object_hook=dict2obj)
  7213. except Exception as e:
  7214. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  7215. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7216. return
  7217. # Clear the current project
  7218. # # NOT THREAD SAFE # ##
  7219. if run_from_arg is True:
  7220. pass
  7221. elif cli is True:
  7222. self.delete_selection_shape()
  7223. else:
  7224. self.on_file_new()
  7225. # Project options
  7226. self.options.update(d['options'])
  7227. self.project_filename = filename
  7228. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7229. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7230. if cli is None:
  7231. self.set_screen_units(self.options["units"])
  7232. # Re create objects
  7233. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  7234. for obj in d['objs']:
  7235. try:
  7236. def obj_init(obj_inst, app_inst):
  7237. obj_inst.from_dict(obj)
  7238. App.log.debug("Recreating from opened project an %s object: %s" %
  7239. (obj['kind'].capitalize(), obj['options']['name']))
  7240. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7241. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7242. if cli is None:
  7243. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"),
  7244. obj['kind'].upper(),
  7245. obj['options']['name']
  7246. )
  7247. )
  7248. self.app_obj.new_object(obj['kind'], obj['options']['name'], obj_init, plot=plot)
  7249. except Exception as e:
  7250. print('App.open_project() --> ' + str(e))
  7251. self.inform.emit('[success] %s: %s' % (_("Project loaded from"), filename))
  7252. self.should_we_save = False
  7253. self.file_opened.emit("project", filename)
  7254. # restore autosaving after a project was loaded
  7255. self.block_autosave = False
  7256. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7257. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7258. if cli is None:
  7259. self.set_ui_title(name=self.project_filename)
  7260. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  7261. def plot_all(self, fit_view=True, muted=False, use_thread=True):
  7262. """
  7263. Re-generates all plots from all objects.
  7264. :param fit_view: if True will plot the objects and will adjust the zoom to fit all plotted objects into view
  7265. :param muted: if True don't print messages
  7266. :param use_thread: if True will use threading for plotting the objects
  7267. :return: None
  7268. """
  7269. self.log.debug("Plot_all()")
  7270. if muted is not True:
  7271. self.inform.emit('[success] %s...' % _("Redrawing all objects"))
  7272. for plot_obj in self.collection.get_list():
  7273. def worker_task(obj):
  7274. with self.proc_container.new("Plotting"):
  7275. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  7276. if fit_view is True:
  7277. self.app_obj.object_plotted.emit(obj)
  7278. if use_thread is True:
  7279. # Send to worker
  7280. self.worker_task.emit({'fcn': worker_task, 'params': [plot_obj]})
  7281. else:
  7282. worker_task(plot_obj)
  7283. def register_folder(self, filename):
  7284. """
  7285. Register the last folder used by the app to open something
  7286. :param filename: the last folder is extracted from the filename
  7287. :return: None
  7288. """
  7289. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  7290. def register_save_folder(self, filename):
  7291. """
  7292. Register the last folder used by the app to save something
  7293. :param filename: the last folder is extracted from the filename
  7294. :return: None
  7295. """
  7296. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  7297. # def set_progress_bar(self, percentage, text=""):
  7298. # """
  7299. # Set a progress bar to a value (percentage)
  7300. #
  7301. # :param percentage: Value set to the progressbar
  7302. # :param text: Not used
  7303. # :return: None
  7304. # """
  7305. # self.ui.progress_bar.setValue(int(percentage))
  7306. def setup_recent_items(self):
  7307. """
  7308. Setup a dictionary with the recent files accessed, organized by type
  7309. :return:
  7310. """
  7311. icons = {
  7312. "gerber": self.resource_location + "/flatcam_icon16.png",
  7313. "excellon": self.resource_location + "/drill16.png",
  7314. 'geometry': self.resource_location + "/geometry16.png",
  7315. "cncjob": self.resource_location + "/cnc16.png",
  7316. "script": self.resource_location + "/script_new24.png",
  7317. "document": self.resource_location + "/notes16_1.png",
  7318. "project": self.resource_location + "/project16.png",
  7319. "svg": self.resource_location + "/geometry16.png",
  7320. "dxf": self.resource_location + "/dxf16.png",
  7321. "pdf": self.resource_location + "/pdf32.png",
  7322. "image": self.resource_location + "/image16.png"
  7323. }
  7324. try:
  7325. image_opener = self.image_tool.import_image
  7326. except AttributeError:
  7327. image_opener = None
  7328. openers = {
  7329. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  7330. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  7331. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  7332. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  7333. "script": lambda fname: self.worker_task.emit({'fcn': self.open_script, 'params': [fname]}),
  7334. "document": None,
  7335. 'project': self.open_project,
  7336. 'svg': self.import_svg,
  7337. 'dxf': self.import_dxf,
  7338. 'image': image_opener,
  7339. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  7340. }
  7341. # Open recent file for files
  7342. try:
  7343. f = open(self.data_path + '/recent.json')
  7344. except IOError:
  7345. App.log.error("Failed to load recent item list.")
  7346. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent item list."))
  7347. return
  7348. try:
  7349. self.recent = json.load(f)
  7350. except json.errors.JSONDecodeError:
  7351. App.log.error("Failed to parse recent item list.")
  7352. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent item list."))
  7353. f.close()
  7354. return
  7355. f.close()
  7356. # Open recent file for projects
  7357. try:
  7358. fp = open(self.data_path + '/recent_projects.json')
  7359. except IOError:
  7360. App.log.error("Failed to load recent project item list.")
  7361. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent projects item list."))
  7362. return
  7363. try:
  7364. self.recent_projects = json.load(fp)
  7365. except json.errors.JSONDecodeError:
  7366. App.log.error("Failed to parse recent project item list.")
  7367. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent project item list."))
  7368. fp.close()
  7369. return
  7370. fp.close()
  7371. # Closure needed to create callbacks in a loop.
  7372. # Otherwise late binding occurs.
  7373. def make_callback(func, fname):
  7374. def opener():
  7375. func(fname)
  7376. return opener
  7377. def reset_recent_files():
  7378. # Reset menu
  7379. self.ui.recent.clear()
  7380. self.recent = []
  7381. try:
  7382. ff = open(self.data_path + '/recent.json', 'w')
  7383. except IOError:
  7384. App.log.error("Failed to open recent items file for writing.")
  7385. return
  7386. json.dump(self.recent, ff)
  7387. def reset_recent_projects():
  7388. # Reset menu
  7389. self.ui.recent_projects.clear()
  7390. self.recent_projects = []
  7391. try:
  7392. frp = open(self.data_path + '/recent_projects.json', 'w')
  7393. except IOError:
  7394. App.log.error("Failed to open recent projects items file for writing.")
  7395. return
  7396. json.dump(self.recent, frp)
  7397. # Reset menu
  7398. self.ui.recent.clear()
  7399. self.ui.recent_projects.clear()
  7400. # Create menu items for projects
  7401. for recent in self.recent_projects:
  7402. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  7403. if recent['kind'] == 'project':
  7404. try:
  7405. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  7406. # Attach callback
  7407. o = make_callback(openers[recent["kind"]], recent['filename'])
  7408. action.triggered.connect(o)
  7409. self.ui.recent_projects.addAction(action)
  7410. except KeyError:
  7411. App.log.error("Unsupported file type: %s" % recent["kind"])
  7412. # Last action in Recent Files menu is one that Clear the content
  7413. clear_action_proj = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  7414. (_("Clear Recent projects")), self)
  7415. clear_action_proj.triggered.connect(reset_recent_projects)
  7416. self.ui.recent_projects.addSeparator()
  7417. self.ui.recent_projects.addAction(clear_action_proj)
  7418. # Create menu items for files
  7419. for recent in self.recent:
  7420. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  7421. if recent['kind'] != 'project':
  7422. try:
  7423. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  7424. # Attach callback
  7425. o = make_callback(openers[recent["kind"]], recent['filename'])
  7426. action.triggered.connect(o)
  7427. self.ui.recent.addAction(action)
  7428. except KeyError:
  7429. App.log.error("Unsupported file type: %s" % recent["kind"])
  7430. # Last action in Recent Files menu is one that Clear the content
  7431. clear_action = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  7432. (_("Clear Recent files")), self)
  7433. clear_action.triggered.connect(reset_recent_files)
  7434. self.ui.recent.addSeparator()
  7435. self.ui.recent.addAction(clear_action)
  7436. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  7437. # self.ui.menufilerecent.set_submenu(recent_menu)
  7438. # recent_menu.show_all()
  7439. # self.ui.recent.show()
  7440. self.log.debug("Recent items list has been populated.")
  7441. def setup_component_editor(self):
  7442. """
  7443. Default text for the Selected tab when is not taken by the Object UI.
  7444. :return:
  7445. """
  7446. # label = QtWidgets.QLabel("Choose an item from Project")
  7447. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  7448. sel_title = QtWidgets.QTextEdit(
  7449. _('<b>Shortcut Key List</b>'))
  7450. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  7451. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  7452. f_settings = QSettings("Open Source", "FlatCAM")
  7453. if f_settings.contains("notebook_font_size"):
  7454. fsize = f_settings.value('notebook_font_size', type=int)
  7455. else:
  7456. fsize = 12
  7457. tsize = fsize + int(fsize / 2)
  7458. # selected_text = (_('''
  7459. # <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span>
  7460. # </p>
  7461. #
  7462. # <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  7463. # The normal flow when working in FlatCAM is the following:</span></p>
  7464. #
  7465. # <ol>
  7466. # <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG
  7467. # file into
  7468. # FlatCAM using either the menu&#39;s, toolbars, key shortcuts or
  7469. # even dragging and dropping the files on the AppGUI.<br />
  7470. # <br />
  7471. # You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp;
  7472. # drop of the
  7473. # file into the FLATCAM AppGUI or through the menu/toolbar links offered within the app.</span><br />
  7474. # &nbsp;</li>
  7475. # <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it
  7476. # and then
  7477. # focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the
  7478. # Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to
  7479. # it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  7480. # <br />
  7481. # If the selection of the object is done on the canvas by single click instead, and the
  7482. # <strong>SELECTED TAB</strong>
  7483. # is in focus, again the object properties will be displayed into the Selected Tab. Alternatively,
  7484. # double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate
  7485. # it even if it was out of focus.<br />
  7486. # <br />
  7487. # You can change the parameters in this screen and the flow direction is like this:<br />
  7488. # <br />
  7489. # <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;
  7490. # <strong> Geometry Object
  7491. # </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object
  7492. # </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in
  7493. # <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  7494. # </ol>
  7495. #
  7496. # <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in
  7497. # <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut:
  7498. # <strong>F3</strong>.</span></p>
  7499. #
  7500. # ''').format(fsize=fsize, tsize=tsize))
  7501. selected_text = '''
  7502. <p><span style="font-size:{tsize}px"><strong>{title}</strong></span></p>
  7503. <p><span style="font-size:{fsize}px"><strong>{subtitle}</strong>:<br />
  7504. {s1}</span></p>
  7505. <ol>
  7506. <li><span style="font-size:{fsize}px">{s2}<br />
  7507. <br />
  7508. {s3}</span><br />
  7509. &nbsp;</li>
  7510. <li><span style="font-size:{fsize}px">{s4}<br />
  7511. &nbsp;</li>
  7512. <br />
  7513. <li><span style="font-size:{fsize}px">{s5}<br />
  7514. &nbsp;</li>
  7515. <br />
  7516. <li><span style="font-size:{fsize}px">{s6}<br />
  7517. <br />
  7518. {s7}</span></li>
  7519. </ol>
  7520. <p><span style="font-size:{fsize}px">{s8}</span></p>
  7521. '''.format(
  7522. title=_("Selected Tab - Choose an Item from Project Tab"),
  7523. subtitle=_("Details"),
  7524. s1=_("The normal flow when working in FlatCAM is the following:"),
  7525. s2=_("Load/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM "
  7526. "using either the toolbars, key shortcuts or even dragging and dropping the "
  7527. "files on the AppGUI."),
  7528. s3=_("You can also load a FlatCAM project by double clicking on the project file, "
  7529. "drag and drop of the file into the FLATCAM AppGUI or through the menu (or toolbar) "
  7530. "actions offered within the app."),
  7531. s4=_("Once an object is available in the Project Tab, by selecting it and then focusing "
  7532. "on SELECTED TAB (more simpler is to double click the object name in the Project Tab, "
  7533. "SELECTED TAB will be updated with the object properties according to its kind: "
  7534. "Gerber, Excellon, Geometry or CNCJob object."),
  7535. s5=_("If the selection of the object is done on the canvas by single click instead, "
  7536. "and the SELECTED TAB is in focus, again the object properties will be displayed into the "
  7537. "Selected Tab. Alternatively, double clicking on the object on the canvas will bring "
  7538. "the SELECTED TAB and populate it even if it was out of focus."),
  7539. s6=_("You can change the parameters in this screen and the flow direction is like this:"),
  7540. s7=_("Gerber/Excellon Object --> Change Parameter --> Generate Geometry --> Geometry Object --> "
  7541. "Add tools (change param in Selected Tab) --> Generate CNCJob --> CNCJob Object --> "
  7542. "Verify GCode (through Edit CNC Code) and/or append/prepend to GCode "
  7543. "(again, done in SELECTED TAB) --> Save GCode."),
  7544. s8=_("A list of key shortcuts is available through an menu entry in Help --> Shortcuts List "
  7545. "or through its own key shortcut: <b>F3</b>."),
  7546. tsize=tsize,
  7547. fsize=fsize
  7548. )
  7549. sel_title.setText(selected_text)
  7550. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  7551. self.ui.selected_scroll_area.setWidget(sel_title)
  7552. def setup_obj_classes(self):
  7553. """
  7554. Sets up application specifics on the FlatCAMObj class. This way the object.app attribute will point to the App
  7555. class.
  7556. :return: None
  7557. """
  7558. FlatCAMObj.app = self
  7559. ObjectCollection.app = self
  7560. Gerber.app = self
  7561. Excellon.app = self
  7562. Geometry.app = self
  7563. CNCjob.app = self
  7564. FCProcess.app = self
  7565. FCProcessContainer.app = self
  7566. OptionsGroupUI.app = self
  7567. def version_check(self):
  7568. """
  7569. Checks for the latest version of the program. Alerts the
  7570. user if theirs is outdated. This method is meant to be run
  7571. in a separate thread.
  7572. :return: None
  7573. """
  7574. self.log.debug("version_check()")
  7575. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  7576. full_url = "%s?s=%s&v=%s&os=%s&%s" % (
  7577. App.version_url,
  7578. str(self.defaults['global_serial']),
  7579. str(self.version),
  7580. str(self.os),
  7581. urllib.parse.urlencode(self.defaults["global_stats"])
  7582. )
  7583. # full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + \
  7584. # "&v=" + str(self.version) + "&os=" + str(self.os) + "&" + \
  7585. # urllib.parse.urlencode(self.defaults["global_stats"])
  7586. else:
  7587. # no_stats dict; just so it won't break things on website
  7588. no_ststs_dict = {}
  7589. no_ststs_dict["global_ststs"] = {}
  7590. full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + "&v=" + str(self.version)
  7591. full_url += "&os=" + str(self.os) + "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  7592. App.log.debug("Checking for updates @ %s" % full_url)
  7593. # ## Get the data
  7594. try:
  7595. f = urllib.request.urlopen(full_url)
  7596. except Exception:
  7597. # App.log.warning("Failed checking for latest version. Could not connect.")
  7598. self.log.warning("Failed checking for latest version. Could not connect.")
  7599. self.inform.emit('[WARNING_NOTCL] %s' % _("Failed checking for latest version. Could not connect."))
  7600. return
  7601. try:
  7602. data = json.load(f)
  7603. except Exception as e:
  7604. App.log.error("Could not parse information about latest version.")
  7605. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not parse information about latest version."))
  7606. App.log.debug("json.load(): %s" % str(e))
  7607. f.close()
  7608. return
  7609. f.close()
  7610. # ## Latest version?
  7611. if self.version >= data["version"]:
  7612. App.log.debug("FlatCAM is up to date!")
  7613. self.inform.emit('[success] %s' % _("FlatCAM is up to date!"))
  7614. return
  7615. App.log.debug("Newer version available.")
  7616. self.message.emit(
  7617. _("Newer Version Available"),
  7618. '%s<br><br>><b>%s</b><br>%s' % (
  7619. _("There is a newer version of FlatCAM available for download:"),
  7620. str(data["name"]),
  7621. str(data["message"])
  7622. ),
  7623. _("info")
  7624. )
  7625. def on_plotcanvas_setup(self, container=None):
  7626. """
  7627. This is doing the setup for the plot area (canvas).
  7628. :param container: QT Widget where to install the canvas
  7629. :return: None
  7630. """
  7631. if container:
  7632. plot_container = container
  7633. else:
  7634. plot_container = self.ui.right_layout
  7635. modifier = QtWidgets.QApplication.queryKeyboardModifiers()
  7636. if self.is_legacy is True or modifier == QtCore.Qt.ControlModifier:
  7637. self.is_legacy = True
  7638. self.defaults["global_graphic_engine"] = "2D"
  7639. self.plotcanvas = PlotCanvasLegacy(plot_container, self)
  7640. else:
  7641. try:
  7642. self.plotcanvas = PlotCanvas(plot_container, self)
  7643. except Exception as er:
  7644. msg_txt = traceback.format_exc()
  7645. log.debug("App.on_plotcanvas_setup() failed -> %s" % str(er))
  7646. log.debug("OpenGL canvas initialization failed with the following error.\n" + msg_txt)
  7647. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  7648. msg += _("OpenGL canvas initialization failed. HW or HW configuration not supported."
  7649. "Change the graphic engine to Legacy(2D) in Edit -> Preferences -> General tab.\n\n")
  7650. msg += msg_txt
  7651. self.inform.emit(msg)
  7652. return 'fail'
  7653. # So it can receive key presses
  7654. self.plotcanvas.native.setFocus()
  7655. if self.is_legacy is False:
  7656. pan_button = 2 if self.defaults["global_pan_button"] == '2' else 3
  7657. # Set the mouse button for panning
  7658. self.plotcanvas.view.camera.pan_button_setting = pan_button
  7659. self.mm = self.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move_over_plot)
  7660. self.mp = self.plotcanvas.graph_event_connect('mouse_press', self.on_mouse_click_over_plot)
  7661. self.mr = self.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release_over_plot)
  7662. self.mdc = self.plotcanvas.graph_event_connect('mouse_double_click', self.on_mouse_double_click_over_plot)
  7663. # Keys over plot enabled
  7664. self.kp = self.plotcanvas.graph_event_connect('key_press', self.ui.keyPressEvent)
  7665. if self.defaults['global_cursor_type'] == 'small':
  7666. self.app_cursor = self.plotcanvas.new_cursor()
  7667. else:
  7668. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  7669. if self.ui.grid_snap_btn.isChecked():
  7670. self.app_cursor.enabled = True
  7671. else:
  7672. self.app_cursor.enabled = False
  7673. if self.is_legacy is False:
  7674. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  7675. else:
  7676. # will use the default Matplotlib axes
  7677. self.hover_shapes = ShapeCollectionLegacy(obj=self, app=self, name='hover')
  7678. def on_zoom_fit(self):
  7679. """
  7680. Callback for zoom-fit request. This can be either from the corresponding
  7681. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  7682. with axes limits from the geometry bounds of all objects.
  7683. :return: None
  7684. """
  7685. if self.is_legacy is False:
  7686. self.plotcanvas.fit_view()
  7687. else:
  7688. xmin, ymin, xmax, ymax = self.collection.get_bounds()
  7689. width = xmax - xmin
  7690. height = ymax - ymin
  7691. xmin -= 0.05 * width
  7692. xmax += 0.05 * width
  7693. ymin -= 0.05 * height
  7694. ymax += 0.05 * height
  7695. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  7696. def on_zoom_in(self):
  7697. """
  7698. Callback for zoom-in request.
  7699. :return:
  7700. """
  7701. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  7702. def on_zoom_out(self):
  7703. """
  7704. Callback for zoom-out request.
  7705. :return:
  7706. """
  7707. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  7708. def disable_all_plots(self):
  7709. self.defaults.report_usage("disable_all_plots()")
  7710. self.disable_plots(self.collection.get_list())
  7711. self.inform.emit('[success] %s' %
  7712. _("All plots disabled."))
  7713. def disable_other_plots(self):
  7714. self.defaults.report_usage("disable_other_plots()")
  7715. self.disable_plots(self.collection.get_non_selected())
  7716. self.inform.emit('[success] %s' %
  7717. _("All non selected plots disabled."))
  7718. def enable_all_plots(self):
  7719. self.defaults.report_usage("enable_all_plots()")
  7720. self.enable_plots(self.collection.get_list())
  7721. self.inform.emit('[success] %s' %
  7722. _("All plots enabled."))
  7723. def on_enable_sel_plots(self):
  7724. log.debug("App.on_enable_sel_plot()")
  7725. object_list = self.collection.get_selected()
  7726. self.enable_plots(objects=object_list)
  7727. self.inform.emit('[success] %s' % _("Selected plots enabled..."))
  7728. def on_disable_sel_plots(self):
  7729. log.debug("App.on_disable_sel_plot()")
  7730. # self.inform.emit(_("Disabling plots ..."))
  7731. object_list = self.collection.get_selected()
  7732. self.disable_plots(objects=object_list)
  7733. self.inform.emit('[success] %s' % _("Selected plots disabled..."))
  7734. def enable_plots(self, objects):
  7735. """
  7736. Enable plots
  7737. :param objects: list of Objects to be enabled
  7738. :return:
  7739. """
  7740. log.debug("Enabling plots ...")
  7741. # self.inform.emit(_("Working ..."))
  7742. for obj in objects:
  7743. if obj.options['plot'] is False:
  7744. obj.options.set_change_callback(lambda x: None)
  7745. obj.options['plot'] = True
  7746. try:
  7747. # only the Gerber obj has on_plot_cb_click() method
  7748. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  7749. # disable this cb while disconnected,
  7750. # in case the operation takes time the user is not allowed to change it
  7751. obj.ui.plot_cb.setDisabled(True)
  7752. except AttributeError:
  7753. pass
  7754. obj.set_form_item("plot")
  7755. try:
  7756. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  7757. obj.ui.plot_cb.setDisabled(False)
  7758. except AttributeError:
  7759. pass
  7760. obj.options.set_change_callback(obj.on_options_change)
  7761. def worker_task(objs):
  7762. with self.proc_container.new(_("Enabling plots ...")):
  7763. for plot_obj in objs:
  7764. # obj.options['plot'] = True
  7765. if isinstance(plot_obj, CNCJobObject):
  7766. plot_obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  7767. else:
  7768. plot_obj.plot(visible=True)
  7769. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  7770. def disable_plots(self, objects):
  7771. """
  7772. Disables plots
  7773. :param objects: list of Objects to be disabled
  7774. :return:
  7775. """
  7776. # if no objects selected then do nothing
  7777. if not self.collection.get_selected():
  7778. return
  7779. log.debug("Disabling plots ...")
  7780. # self.inform.emit(_("Working ..."))
  7781. for obj in objects:
  7782. if obj.options['plot'] is True:
  7783. obj.options.set_change_callback(lambda x: None)
  7784. obj.options['plot'] = False
  7785. try:
  7786. # only the Gerber obj has on_plot_cb_click() method
  7787. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  7788. obj.ui.plot_cb.setDisabled(True)
  7789. except AttributeError:
  7790. pass
  7791. obj.set_form_item("plot")
  7792. try:
  7793. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  7794. obj.ui.plot_cb.setDisabled(False)
  7795. except AttributeError:
  7796. pass
  7797. obj.options.set_change_callback(obj.on_options_change)
  7798. try:
  7799. self.delete_selection_shape()
  7800. except Exception as e:
  7801. log.debug("App.disable_plots() --> %s" % str(e))
  7802. def worker_task(objs):
  7803. with self.proc_container.new(_("Disabling plots ...")):
  7804. for plot_obj in objs:
  7805. # obj.options['plot'] = True
  7806. if isinstance(plot_obj, CNCJobObject):
  7807. plot_obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  7808. else:
  7809. plot_obj.plot(visible=False)
  7810. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  7811. def toggle_plots(self, objects):
  7812. """
  7813. Toggle plots visibility
  7814. :param objects: list of Objects for which to be toggled the visibility
  7815. :return: None
  7816. """
  7817. # if no objects selected then do nothing
  7818. if not self.collection.get_selected():
  7819. return
  7820. log.debug("Toggling plots ...")
  7821. self.inform.emit(_("Working ..."))
  7822. for obj in objects:
  7823. if obj.options['plot'] is False:
  7824. obj.options['plot'] = True
  7825. else:
  7826. obj.options['plot'] = False
  7827. self.app_obj.plots_updated.emit()
  7828. def clear_plots(self):
  7829. """
  7830. Clear the plots
  7831. :return: None
  7832. """
  7833. objects = self.collection.get_list()
  7834. for obj in objects:
  7835. obj.clear(obj == objects[-1])
  7836. # Clear pool to free memory
  7837. self.clear_pool()
  7838. def on_set_color_action_triggered(self):
  7839. """
  7840. This slot gets called by clicking on the menu entry in the Set Color submenu of the context menu in Project Tab
  7841. :return:
  7842. """
  7843. new_color = self.defaults['gerber_plot_fill']
  7844. clicked_action = self.sender()
  7845. assert isinstance(clicked_action, QAction), "Expected a QAction, got %s" % type(clicked_action)
  7846. act_name = clicked_action.text()
  7847. sel_obj_list = self.collection.get_selected()
  7848. if not sel_obj_list:
  7849. return
  7850. # a default value, I just chose this one
  7851. alpha_level = 'BF'
  7852. for sel_obj in sel_obj_list:
  7853. if sel_obj.kind == 'excellon':
  7854. alpha_level = str(hex(
  7855. self.ui.excellon_defaults_form.excellon_gen_group.color_alpha_slider.value())[2:])
  7856. elif sel_obj.kind == 'gerber':
  7857. alpha_level = str(hex(self.ui.gerber_defaults_form.gerber_gen_group.pf_color_alpha_slider.value())[2:])
  7858. elif sel_obj.kind == 'geometry':
  7859. alpha_level = 'FF'
  7860. else:
  7861. log.debug(
  7862. "App.on_set_color_action_triggered() --> Default alpfa for this object type not supported yet")
  7863. continue
  7864. sel_obj.alpha_level = alpha_level
  7865. if act_name == _('Red'):
  7866. new_color = '#FF0000' + alpha_level
  7867. if act_name == _('Blue'):
  7868. new_color = '#0000FF' + alpha_level
  7869. if act_name == _('Yellow'):
  7870. new_color = '#FFDF00' + alpha_level
  7871. if act_name == _('Green'):
  7872. new_color = '#00FF00' + alpha_level
  7873. if act_name == _('Purple'):
  7874. new_color = '#FF00FF' + alpha_level
  7875. if act_name == _('Brown'):
  7876. new_color = '#A52A2A' + alpha_level
  7877. if act_name == _('White'):
  7878. new_color = '#FFFFFF' + alpha_level
  7879. if act_name == _('Black'):
  7880. new_color = '#000000' + alpha_level
  7881. if act_name == _('Custom'):
  7882. new_color = QtGui.QColor(self.defaults['gerber_plot_fill'][:7])
  7883. c_dialog = QtWidgets.QColorDialog()
  7884. plot_fill_color = c_dialog.getColor(initial=new_color)
  7885. if plot_fill_color.isValid() is False:
  7886. return
  7887. new_color = str(plot_fill_color.name()) + alpha_level
  7888. if act_name == _("Default"):
  7889. for sel_obj in sel_obj_list:
  7890. if sel_obj.kind == 'excellon':
  7891. new_color = self.defaults['excellon_plot_fill']
  7892. new_line_color = self.defaults['excellon_plot_line']
  7893. elif sel_obj.kind == 'gerber':
  7894. new_color = self.defaults['gerber_plot_fill']
  7895. new_line_color = self.defaults['gerber_plot_line']
  7896. elif sel_obj.kind == 'geometry':
  7897. new_color = self.defaults['geometry_plot_line']
  7898. new_line_color = self.defaults['geometry_plot_line']
  7899. else:
  7900. log.debug(
  7901. "App.on_set_color_action_triggered() --> Default color for this object type not supported yet")
  7902. continue
  7903. sel_obj.fill_color = new_color
  7904. sel_obj.outline_color = new_line_color
  7905. sel_obj.shapes.redraw(
  7906. update_colors=(new_color, new_line_color)
  7907. )
  7908. return
  7909. if act_name == _("Opacity"):
  7910. alpha_level, ok_button = QtWidgets.QInputDialog.getInt(
  7911. self.ui, _("Set alpha level ..."), '%s:' % _("Value"), min=0, max=255, step=1, value=191)
  7912. if ok_button:
  7913. alpha_str = str(hex(alpha_level)[2:]) if alpha_level != 0 else '00'
  7914. for sel_obj in sel_obj_list:
  7915. sel_obj.fill_color = sel_obj.fill_color[:-2] + alpha_str
  7916. sel_obj.shapes.redraw(
  7917. update_colors=(sel_obj.fill_color, sel_obj.outline_color)
  7918. )
  7919. return
  7920. new_line_color = color_variant(new_color[:7], 0.7)
  7921. if act_name == _("White"):
  7922. new_line_color = color_variant("#dedede", 0.7)
  7923. for sel_obj in sel_obj_list:
  7924. sel_obj.fill_color = new_color
  7925. sel_obj.outline_color = new_line_color
  7926. sel_obj.shapes.redraw(
  7927. update_colors=(new_color, new_line_color)
  7928. )
  7929. def generate_cnc_job(self, objects):
  7930. """
  7931. Slot that will be called by clicking an entry in the contextual menu generated in the Project Tab tree
  7932. :param objects: Selected objects in the Project Tab
  7933. :return:
  7934. """
  7935. self.defaults.report_usage("generate_cnc_job()")
  7936. # for obj in objects:
  7937. # obj.generatecncjob()
  7938. for obj in objects:
  7939. obj.on_generatecnc_button_click()
  7940. def save_project(self, filename, quit_action=False, silent=False, from_tcl=False):
  7941. """
  7942. Saves the current project to the specified file.
  7943. :param filename: Name of the file in which to save.
  7944. :type filename: str
  7945. :param quit_action: if the project saving will be followed by an app quit; boolean
  7946. :param silent: if True will not display status messages
  7947. :param from_tcl True is run from Tcl Shell
  7948. :return: None
  7949. """
  7950. self.log.debug("save_project()")
  7951. self.save_in_progress = True
  7952. with self.proc_container.new(_("Saving FlatCAM Project")):
  7953. # Capture the latest changes
  7954. # Current object
  7955. try:
  7956. current_object = self.collection.get_active()
  7957. if current_object:
  7958. current_object.read_form()
  7959. except Exception as e:
  7960. self.log.debug("save_project() --> There was no active object. Skipping read_form. %s" % str(e))
  7961. pass
  7962. # Serialize the whole project
  7963. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  7964. "options": self.options,
  7965. "version": self.version}
  7966. if self.defaults["global_save_compressed"] is True:
  7967. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  7968. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  7969. # # Write
  7970. f.write(g)
  7971. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  7972. else:
  7973. # Open file
  7974. try:
  7975. f = open(filename, 'w')
  7976. except IOError:
  7977. App.log.error("Failed to open file for saving: %s", filename)
  7978. self.inform.emit('[ERROR_NOTCL] %s' % _("The object is used by another application."))
  7979. return
  7980. # Write
  7981. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  7982. f.close()
  7983. # verification of the saved project
  7984. # Open and parse
  7985. try:
  7986. saved_f = open(filename, 'r')
  7987. except IOError:
  7988. if silent is False:
  7989. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  7990. (_("Failed to verify project file"), filename, _("Retry to save it.")))
  7991. return
  7992. try:
  7993. saved_d = json.load(saved_f, object_hook=dict2obj)
  7994. except Exception:
  7995. if silent is False:
  7996. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  7997. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  7998. f.close()
  7999. return
  8000. saved_f.close()
  8001. if silent is False:
  8002. if 'version' in saved_d:
  8003. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8004. else:
  8005. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8006. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8007. tb_settings = QSettings("Open Source", "FlatCAM")
  8008. lock_state = self.ui.lock_action.isChecked()
  8009. tb_settings.setValue('toolbar_lock', lock_state)
  8010. # This will write the setting to the platform specific storage.
  8011. del tb_settings
  8012. # if quit:
  8013. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  8014. # t.start()
  8015. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  8016. def start_delayed_quit(self, delay, filename, should_quit=None):
  8017. """
  8018. :param delay: period of checking if project file size is more than zero; in seconds
  8019. :param filename: the name of the project file to be checked periodically for size more than zero
  8020. :param should_quit: if the task finished will be followed by an app quit; boolean
  8021. :return:
  8022. """
  8023. to_quit = should_quit
  8024. self.save_timer = QtCore.QTimer()
  8025. self.save_timer.setInterval(delay)
  8026. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  8027. self.save_timer.start()
  8028. def check_project_file_size(self, filename, should_quit=None):
  8029. """
  8030. :param filename: the name of the project file to be checked periodically for size more than zero
  8031. :param should_quit: will quit the app if True; boolean
  8032. :return:
  8033. """
  8034. try:
  8035. if os.stat(filename).st_size > 0:
  8036. self.save_in_progress = False
  8037. self.save_timer.stop()
  8038. if should_quit:
  8039. self.app_quit.emit()
  8040. except Exception:
  8041. traceback.print_exc()
  8042. def save_project_auto(self):
  8043. """
  8044. Called periodically to save the project.
  8045. It will save if there is no block on the save, if the project was saved at least once and if there is no save in
  8046. # progress.
  8047. :return:
  8048. """
  8049. if self.block_autosave is False and self.should_we_save is True and self.save_in_progress is False:
  8050. self.on_file_saveproject()
  8051. def save_project_auto_update(self):
  8052. """
  8053. Update the auto save time interval value.
  8054. :return:
  8055. """
  8056. log.debug("App.save_project_auto_update() --> updated the interval timeout.")
  8057. try:
  8058. if self.autosave_timer.isActive():
  8059. self.autosave_timer.stop()
  8060. except Exception:
  8061. pass
  8062. if self.defaults['global_autosave'] is True:
  8063. self.autosave_timer.setInterval(int(self.defaults['global_autosave_timeout']))
  8064. self.autosave_timer.start()
  8065. def on_options_app2project(self):
  8066. """
  8067. Callback for Options->Transfer Options->App=>Project. Copies options
  8068. from application defaults to project defaults.
  8069. :return: None
  8070. """
  8071. self.defaults.report_usage("on_options_app2project")
  8072. self.preferencesUiManager.defaults_read_form()
  8073. self.options.update(self.defaults)
  8074. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  8075. """
  8076. Shows a message on the FlatCAM Shell
  8077. :param msg: Message to display.
  8078. :param show: Opens the shell.
  8079. :param error: Shows the message as an error.
  8080. :param warning: Shows the message as an warning.
  8081. :param success: Shows the message as an success.
  8082. :param selected: Indicate that something was selected on canvas
  8083. :return: None
  8084. """
  8085. if show:
  8086. self.ui.shell_dock.show()
  8087. try:
  8088. if error:
  8089. self.shell.append_error(msg + "\n")
  8090. elif warning:
  8091. self.shell.append_warning(msg + "\n")
  8092. elif success:
  8093. self.shell.append_success(msg + "\n")
  8094. elif selected:
  8095. self.shell.append_selected(msg + "\n")
  8096. else:
  8097. self.shell.append_output(msg + "\n")
  8098. except AttributeError:
  8099. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  8100. class ArgsThread(QtCore.QObject):
  8101. open_signal = pyqtSignal(list)
  8102. start = pyqtSignal()
  8103. stop = pyqtSignal()
  8104. if sys.platform == 'win32':
  8105. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  8106. else:
  8107. address = ('/tmp/testipc', 'AF_UNIX')
  8108. def __init__(self):
  8109. super(ArgsThread, self).__init__()
  8110. self.listener = None
  8111. self.thread_exit = False
  8112. self.start.connect(self.run)
  8113. self.stop.connect(self.close_listener)
  8114. def my_loop(self, address):
  8115. try:
  8116. self.listener = Listener(*address)
  8117. while self.thread_exit is False:
  8118. conn = self.listener.accept()
  8119. self.serve(conn)
  8120. except socket.error:
  8121. try:
  8122. conn = Client(*address)
  8123. conn.send(sys.argv)
  8124. conn.send('close')
  8125. # close the current instance only if there are args
  8126. if len(sys.argv) > 1:
  8127. try:
  8128. self.listener.close()
  8129. except Exception:
  8130. pass
  8131. sys.exit()
  8132. except ConnectionRefusedError:
  8133. if sys.platform == 'win32':
  8134. pass
  8135. else:
  8136. os.system('rm /tmp/testipc')
  8137. self.listener = Listener(*address)
  8138. while True:
  8139. conn = self.listener.accept()
  8140. self.serve(conn)
  8141. def serve(self, conn):
  8142. while self.thread_exit is False:
  8143. msg = conn.recv()
  8144. if msg == 'close':
  8145. break
  8146. self.open_signal.emit(msg)
  8147. conn.close()
  8148. # the decorator is a must; without it this technique will not work unless the start signal is connected
  8149. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  8150. @pyqtSlot()
  8151. def run(self):
  8152. self.my_loop(self.address)
  8153. @pyqtSlot()
  8154. def close_listener(self):
  8155. self.thread_exit = True
  8156. self.listener.close()
  8157. # end of file