App_Main.py 443 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907
  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)
  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.connect(self.info)
  606. # signal to be called when the app is quiting
  607. self.app_quit.connect(self.quit_application, type=Qt.QueuedConnection)
  608. self.message.connect(lambda: message_dialog(parent=self.ui))
  609. # self.progress.connect(self.set_progress_bar)
  610. # signals emitted when file state change
  611. self.file_opened.connect(self.register_recent)
  612. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  613. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  614. # ########################################## Standard signals ###############################################
  615. # ### Menu
  616. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  617. self.ui.menufilenewgeo.triggered.connect(self.app_obj.new_geometry_object)
  618. self.ui.menufilenewgrb.triggered.connect(self.app_obj.new_gerber_object)
  619. self.ui.menufilenewexc.triggered.connect(self.app_obj.new_excellon_object)
  620. self.ui.menufilenewdoc.triggered.connect(self.app_obj.new_document_object)
  621. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  622. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  623. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  624. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  625. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  626. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  627. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  628. self.ui.menufileopenscriptexample.triggered.connect(self.on_fileopenscript_example)
  629. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  630. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  631. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  632. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  633. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  634. self.ui.menufileimport_hpgl2_as_geo.triggered.connect(self.on_fileopenhpgl2)
  635. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  636. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  637. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  638. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  639. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  640. self.ui.menufile_print.triggered.connect(lambda: self.on_file_save_objects_pdf(use_thread=True))
  641. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  642. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  643. # self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  644. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  645. self.ui.menufileexportpref.triggered.connect(self.on_export_preferences)
  646. self.ui.menufileimportpref.triggered.connect(self.on_import_preferences)
  647. self.ui.menufile_exit.triggered.connect(self.final_save)
  648. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  649. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  650. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  651. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  652. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  653. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  654. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  655. self.ui.menueditdelete.triggered.connect(self.on_delete)
  656. self.ui.menueditcopyobject.triggered.connect(self.on_copy_command)
  657. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  658. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  659. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  660. self.ui.menuedit_move2origin.triggered.connect(self.on_move2origin)
  661. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  662. self.ui.menueditlocate.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  663. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  664. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  665. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  666. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  667. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  668. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  669. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  670. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  671. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  672. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  673. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  674. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  675. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  676. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  677. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  678. self.ui.menuoptions_tools_db.triggered.connect(lambda: self.on_tools_database(source='app'))
  679. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  680. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  681. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  682. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  683. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  684. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  685. self.ui.menuview_replot.triggered.connect(self.plot_all)
  686. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  687. self.ui.menuview_toggle_fscreen.triggered.connect(self.ui.on_fullscreen)
  688. self.ui.menuview_toggle_parea.triggered.connect(self.ui.on_toggle_plotarea)
  689. self.ui.menuview_toggle_notebook.triggered.connect(self.ui.on_toggle_notebook)
  690. self.ui.menu_toggle_nb.triggered.connect(self.ui.on_toggle_notebook)
  691. self.ui.menuview_toggle_grid.triggered.connect(self.ui.on_toggle_grid)
  692. self.ui.menuview_toggle_grid_lines.triggered.connect(self.on_toggle_grid_lines)
  693. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  694. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_toggle)
  695. self.ui.menuview_toggle_hud.triggered.connect(self.on_toggle_hud)
  696. self.ui.menutoolshell.triggered.connect(self.ui.toggle_shell_ui)
  697. self.ui.menuhelp_about.triggered.connect(self.on_about)
  698. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  699. self.ui.menuhelp_report_bug.triggered.connect(lambda: webbrowser.open(self.bug_report_url))
  700. self.ui.menuhelp_exc_spec.triggered.connect(lambda: webbrowser.open(self.excellon_spec_url))
  701. self.ui.menuhelp_gerber_spec.triggered.connect(lambda: webbrowser.open(self.gerber_spec_url))
  702. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  703. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  704. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  705. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  706. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  707. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  708. self.ui.menuprojectcopy.triggered.connect(self.on_copy_command)
  709. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  710. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  711. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  712. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  713. # ToolBar signals
  714. self.connect_toolbar_signals()
  715. # Notebook and Plot Tab Area signals
  716. # make the right click on the notebook tab and plot tab area tab raise a menu
  717. self.ui.notebook.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  718. self.ui.plot_tab_area.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  719. self.on_tab_setup_context_menu()
  720. # activate initial state
  721. self.on_tab_rmb_click(self.defaults["global_tabs_detachable"])
  722. # Context Menu
  723. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  724. self.ui.popmenu_panel_toggle.triggered.connect(self.ui.on_toggle_notebook)
  725. self.ui.popmenu_new_geo.triggered.connect(self.app_obj.new_geometry_object)
  726. self.ui.popmenu_new_grb.triggered.connect(self.app_obj.new_gerber_object)
  727. self.ui.popmenu_new_exc.triggered.connect(self.app_obj.new_excellon_object)
  728. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  729. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  730. self.ui.clearplot.triggered.connect(self.clear_plots)
  731. self.ui.replot.triggered.connect(self.plot_all)
  732. self.ui.popmenu_copy.triggered.connect(self.on_copy_command)
  733. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  734. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  735. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  736. self.ui.popmenu_move.triggered.connect(self.obj_move)
  737. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  738. # Project Context Menu -> Color Setting
  739. for act in self.ui.menuprojectcolor.actions():
  740. act.triggered.connect(self.on_set_color_action_triggered)
  741. # ###########################################################################################################
  742. # #################################### GUI PREFERENCES SIGNALS ##############################################
  743. # ###########################################################################################################
  744. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  745. lambda: self.on_toggle_units(no_pref=False))
  746. # ##################################### Workspace Setting Signals ###########################################
  747. self.ui.general_defaults_form.general_app_set_group.wk_cb.currentIndexChanged.connect(
  748. self.on_workspace_modified)
  749. self.ui.general_defaults_form.general_app_set_group.wk_orientation_radio.activated_custom.connect(
  750. self.on_workspace_modified
  751. )
  752. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  753. # ###########################################################################################################
  754. # ######################################## GUI SETTINGS SIGNALS #############################################
  755. # ###########################################################################################################
  756. self.ui.general_defaults_form.general_app_set_group.cursor_radio.activated_custom.connect(self.on_cursor_type)
  757. # ######################################## Tools related signals ############################################
  758. # portability changed signal
  759. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  760. # Object list
  761. self.object_status_changed.connect(self.collection.on_collection_updated)
  762. # when there are arguments at application startup this get launched
  763. self.args_at_startup[list].connect(self.on_startup_args)
  764. # ###########################################################################################################
  765. # ####################################### FILE ASSOCIATIONS SIGNALS #########################################
  766. # ###########################################################################################################
  767. self.ui.util_defaults_form.fa_excellon_group.restore_btn.clicked.connect(
  768. lambda: self.restore_extensions(ext_type='excellon'))
  769. self.ui.util_defaults_form.fa_gcode_group.restore_btn.clicked.connect(
  770. lambda: self.restore_extensions(ext_type='gcode'))
  771. self.ui.util_defaults_form.fa_gerber_group.restore_btn.clicked.connect(
  772. lambda: self.restore_extensions(ext_type='gerber'))
  773. self.ui.util_defaults_form.fa_excellon_group.del_all_btn.clicked.connect(
  774. lambda: self.delete_all_extensions(ext_type='excellon'))
  775. self.ui.util_defaults_form.fa_gcode_group.del_all_btn.clicked.connect(
  776. lambda: self.delete_all_extensions(ext_type='gcode'))
  777. self.ui.util_defaults_form.fa_gerber_group.del_all_btn.clicked.connect(
  778. lambda: self.delete_all_extensions(ext_type='gerber'))
  779. self.ui.util_defaults_form.fa_excellon_group.add_btn.clicked.connect(
  780. lambda: self.add_extension(ext_type='excellon'))
  781. self.ui.util_defaults_form.fa_gcode_group.add_btn.clicked.connect(
  782. lambda: self.add_extension(ext_type='gcode'))
  783. self.ui.util_defaults_form.fa_gerber_group.add_btn.clicked.connect(
  784. lambda: self.add_extension(ext_type='gerber'))
  785. self.ui.util_defaults_form.fa_excellon_group.del_btn.clicked.connect(
  786. lambda: self.del_extension(ext_type='excellon'))
  787. self.ui.util_defaults_form.fa_gcode_group.del_btn.clicked.connect(
  788. lambda: self.del_extension(ext_type='gcode'))
  789. self.ui.util_defaults_form.fa_gerber_group.del_btn.clicked.connect(
  790. lambda: self.del_extension(ext_type='gerber'))
  791. # connect the 'Apply' buttons from the Preferences/File Associations
  792. self.ui.util_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  793. lambda: self.on_register_files(obj_type='excellon'))
  794. self.ui.util_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  795. lambda: self.on_register_files(obj_type='gcode'))
  796. self.ui.util_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  797. lambda: self.on_register_files(obj_type='gerber'))
  798. # ###########################################################################################################
  799. # ########################################### KEYWORDS SIGNALS ##############################################
  800. # ###########################################################################################################
  801. self.ui.util_defaults_form.kw_group.restore_btn.clicked.connect(
  802. lambda: self.restore_extensions(ext_type='keyword'))
  803. self.ui.util_defaults_form.kw_group.del_all_btn.clicked.connect(
  804. lambda: self.delete_all_extensions(ext_type='keyword'))
  805. self.ui.util_defaults_form.kw_group.add_btn.clicked.connect(
  806. lambda: self.add_extension(ext_type='keyword'))
  807. self.ui.util_defaults_form.kw_group.del_btn.clicked.connect(
  808. lambda: self.del_extension(ext_type='keyword'))
  809. # connect the abort_all_tasks related slots to the related signals
  810. self.proc_container.idle_flag.connect(self.app_is_idle)
  811. # signal emitted when a tab is closed in the Plot Area
  812. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_plot_area_tab_closed)
  813. # signal to close the application
  814. self.close_app_signal.connect(self.kill_app)
  815. # ################################# FINISHED CONNECTING SIGNALS #############################################
  816. # ###########################################################################################################
  817. # ###########################################################################################################
  818. # ###########################################################################################################
  819. self.log.debug("Finished connecting Signals.")
  820. # ###########################################################################################################
  821. # ########################################## Other setups ###################################################
  822. # ###########################################################################################################
  823. # to use for tools like Distance tool who depends on the event sources who are changed inside the AppEditors
  824. # depending on from where those tools are called different actions can be done
  825. self.call_source = 'app'
  826. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  827. self.tool_tab_locked = False
  828. # decide if to show or hide the Notebook side of the screen at startup
  829. if self.defaults["global_project_at_startup"] is True:
  830. self.ui.splitter.setSizes([1, 1])
  831. else:
  832. self.ui.splitter.setSizes([0, 1])
  833. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  834. self.setup_component_editor()
  835. # ###########################################################################################################
  836. # ####################################### Auto-complete KEYWORDS ############################################
  837. # ###########################################################################################################
  838. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  839. 'aligndrill', 'aligndrillgrid', 'bbox', 'clear', 'cncjob', 'cutout',
  840. 'del', 'drillcncjob', 'export_dxf', 'edxf', 'export_excellon',
  841. 'export_exc',
  842. 'export_gcode', 'export_gerber', 'export_svg', 'ext', 'exteriors', 'follow',
  843. 'geo_union', 'geocutout', 'get_bounds', 'get_names', 'get_path', 'get_sys', 'help',
  844. 'interiors', 'isolate', 'join_excellon',
  845. 'join_geometry', 'list_sys', 'milld', 'mills', 'milldrills', 'millslots',
  846. 'mirror', 'ncc',
  847. 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  848. 'open_dxf', 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'open_svg',
  849. 'options', 'origin',
  850. 'paint', 'panelize', 'plot_all', 'plot_objects', 'plot_status', 'quit_flatcam',
  851. 'save', 'save_project',
  852. 'save_sys', 'scale', 'set_active', 'set_origin', 'set_path', 'set_sys',
  853. 'skew', 'subtract_poly', 'subtract_rectangle',
  854. 'version', 'write_gcode'
  855. ]
  856. self.default_keywords = ['Desktop', 'Documents', 'FlatConfig', 'FlatPrj', 'False', 'Marius', 'My Documents',
  857. 'Paste_1',
  858. 'Repetier', 'Roland_MDX_20', 'Users', 'Toolchange_Custom', 'Toolchange_Probe_MACH3',
  859. 'Toolchange_manual', 'True', 'Users',
  860. 'all', 'auto', 'axis',
  861. 'axisoffset', 'box', 'center_x', 'center_y', 'columns', 'combine', 'connect',
  862. 'contour', 'default',
  863. 'depthperpass', 'dia', 'diatol', 'dist', 'drilled_dias', 'drillz', 'dpp',
  864. 'dwelltime', 'extracut_length', 'endxy', 'enz', 'f', 'feedrate',
  865. 'feedrate_z', 'grbl_11', 'GRBL_laser', 'gridoffsety', 'gridx', 'gridy',
  866. 'has_offset', 'holes', 'hpgl', 'iso_type', 'line_xyz', 'margin', 'marlin', 'method',
  867. 'milled_dias', 'minoffset', 'name', 'offset', 'opt_type', 'order',
  868. 'outname', 'overlap', 'passes', 'postamble', 'pp', 'ppname_e', 'ppname_g',
  869. 'preamble', 'radius', 'ref', 'rest', 'rows', 'shellvar_', 'scale_factor',
  870. 'spacing_columns',
  871. 'spacing_rows', 'spindlespeed', 'startz', 'startxy',
  872. 'toolchange_xy', 'toolchangez', 'travelz',
  873. 'tooldia', 'use_threads', 'value',
  874. 'x', 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  875. ]
  876. self.tcl_keywords = [
  877. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  878. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  879. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  880. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  881. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  882. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  883. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  884. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  885. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  886. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  887. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  888. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  889. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  890. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  891. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  892. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  893. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  894. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  895. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  896. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  897. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  898. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  899. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  900. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  901. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  902. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  903. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  904. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  905. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  906. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  907. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  908. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  909. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  910. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  911. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  912. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  913. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  914. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  915. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  916. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  917. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  918. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  919. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  920. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  921. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  922. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  923. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  924. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  925. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  926. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  927. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  928. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  929. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  930. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  931. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  932. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  933. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  934. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  935. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  936. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  937. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  938. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  939. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  940. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  941. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  942. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  943. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  944. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  945. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  946. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  947. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  948. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  949. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  950. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  951. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  952. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  953. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  954. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  955. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  956. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  957. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  958. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  959. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  960. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  961. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  962. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  963. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  964. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  965. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  966. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  967. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  968. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  969. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  970. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  971. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  972. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  973. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  974. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  975. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  976. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  977. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  978. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  979. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  980. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  981. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  982. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  983. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  984. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  985. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  986. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  987. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  988. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  989. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  990. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  991. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  992. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  993. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  994. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  995. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  996. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  997. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  998. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  999. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  1000. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  1001. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  1002. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  1003. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  1004. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  1005. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  1006. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  1007. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  1008. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  1009. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  1010. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  1011. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  1012. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  1013. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  1014. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  1015. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  1016. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  1017. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  1018. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  1019. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  1020. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  1021. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  1022. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  1023. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  1024. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  1025. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  1026. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  1027. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  1028. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  1029. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  1030. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  1031. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  1032. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  1033. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  1034. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  1035. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  1036. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  1037. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  1038. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  1039. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  1040. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  1041. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  1042. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  1043. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  1044. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  1045. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  1046. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  1047. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  1048. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  1049. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  1050. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  1051. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  1052. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  1053. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  1054. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  1055. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  1056. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  1057. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  1058. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  1059. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  1060. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  1061. ]
  1062. self.autocomplete_kw_list = self.defaults['util_autocomplete_keywords'].replace(' ', '').split(',')
  1063. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  1064. # ###########################################################################################################
  1065. # ############################################## Shell SETUP ################################################
  1066. # ###########################################################################################################
  1067. self.shell = FCShell(app=self, version=self.version)
  1068. self.ui.shell_dock.setWidget(self.shell)
  1069. self.log.debug("TCL Shell has been initialized.")
  1070. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  1071. if self.defaults["global_shell_at_startup"]:
  1072. self.ui.shell_dock.show()
  1073. else:
  1074. self.ui.shell_dock.hide()
  1075. # ###########################################################################################################
  1076. # ########################################## Tools and Plugins ##############################################
  1077. # ###########################################################################################################
  1078. self.dblsidedtool = None
  1079. self.distance_tool = None
  1080. self.distance_min_tool = None
  1081. self.panelize_tool = None
  1082. self.film_tool = None
  1083. self.paste_tool = None
  1084. self.calculator_tool = None
  1085. self.rules_tool = None
  1086. self.sub_tool = None
  1087. self.move_tool = None
  1088. self.cutout_tool = None
  1089. self.ncclear_tool = None
  1090. self.paint_tool = None
  1091. self.isolation_tool = None
  1092. self.optimal_tool = None
  1093. self.transform_tool = None
  1094. self.properties_tool = None
  1095. self.pdf_tool = None
  1096. self.image_tool = None
  1097. self.pcb_wizard_tool = None
  1098. self.cal_exc_tool = None
  1099. self.qrcode_tool = None
  1100. self.copper_thieving_tool = None
  1101. self.fiducial_tool = None
  1102. self.edrills_tool = None
  1103. self.align_objects_tool = None
  1104. self.punch_tool = None
  1105. self.invert_tool = None
  1106. self.corners_tool = None
  1107. self.etch_tool = None
  1108. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  1109. try:
  1110. self.install_tools()
  1111. except AttributeError as e:
  1112. log.debug("App.__init__() install tools() --> %s" % str(e))
  1113. # ###########################################################################################################
  1114. # ############################################ SETUP RECENT ITEMS ###########################################
  1115. # ###########################################################################################################
  1116. self.setup_recent_items()
  1117. # ###########################################################################################################
  1118. # ######################################### BookMarks Manager ###############################################
  1119. # ###########################################################################################################
  1120. # install Bookmark Manager and populate bookmarks in the Help -> Bookmarks
  1121. self.install_bookmarks()
  1122. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"])
  1123. # ###########################################################################################################
  1124. # ########################################### Tools Database ################################################
  1125. # ###########################################################################################################
  1126. self.tools_db_tab = None
  1127. # ### System Font Parsing ###
  1128. # self.f_parse = ParseFont(self)
  1129. # self.parse_system_fonts()
  1130. # ###########################################################################################################
  1131. # ######################################### Check for updates ###############################################
  1132. # ###########################################################################################################
  1133. # Separate thread (Not worker)
  1134. # Check for updates on startup but only if the user consent and the app is not in Beta version
  1135. if (self.beta is False or self.beta is None) and \
  1136. self.ui.general_defaults_form.general_app_group.version_check_cb.get_value() is True:
  1137. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  1138. # self.thr2 = QtCore.QThread()
  1139. self.worker_task.emit({'fcn': self.version_check,
  1140. 'params': []})
  1141. # self.thr2.start(QtCore.QThread.LowPriority)
  1142. # ###########################################################################################################
  1143. # ##################################### Register files with FlatCAM; #######################################
  1144. # ################################### It works only for Windows for now ####################################
  1145. # ###########################################################################################################
  1146. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  1147. self.on_register_files()
  1148. # ###########################################################################################################
  1149. # ######################################## Variables for global usage #######################################
  1150. # ###########################################################################################################
  1151. # hold the App units
  1152. self.units = 'MM'
  1153. # coordinates for relative position display
  1154. self.rel_point1 = (0, 0)
  1155. self.rel_point2 = (0, 0)
  1156. # variable to store coordinates
  1157. self.pos = (0, 0)
  1158. self.pos_canvas = (0, 0)
  1159. self.pos_jump = (0, 0)
  1160. # variable to store mouse coordinates
  1161. self.mouse = [0, 0]
  1162. # variable to store the delta positions on cavnas
  1163. self.dx = 0
  1164. self.dy = 0
  1165. # decide if we have a double click or single click
  1166. self.doubleclick = False
  1167. # store here the is_dragging value
  1168. self.event_is_dragging = False
  1169. # variable to store if a command is active (then the var is not None) and which one it is
  1170. self.command_active = None
  1171. # variable to store the status of moving selection action
  1172. # None value means that it's not an selection action
  1173. # True value = a selection from left to right
  1174. # False value = a selection from right to left
  1175. self.selection_type = None
  1176. # List to store the objects that are currently loaded in FlatCAM
  1177. # This list is updated on each object creation or object delete
  1178. self.all_objects_list = []
  1179. self.objects_under_the_click_list = []
  1180. # List to store the objects that are selected
  1181. self.sel_objects_list = []
  1182. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  1183. self.key_modifiers = None
  1184. # Variable to hold the status of the axis
  1185. self.toggle_axis = True
  1186. # Variable to hold the status of the grid lines
  1187. self.toggle_grid_lines = True
  1188. # Variable to store the status of the code editor
  1189. self.toggle_codeeditor = False
  1190. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  1191. self.click_noproject = False
  1192. self.cursor = None
  1193. # Variable to store the GCODE that was edited
  1194. self.gcode_edited = ""
  1195. self.text_editor_tab = None
  1196. # reference for the self.ui.code_editor
  1197. self.reference_code_editor = None
  1198. self.script_code = ''
  1199. # if Tools DB are changed/edited in the Edit -> Tools Database tab the value will be set to True
  1200. self.tools_db_changed_flag = False
  1201. self.grb_list = ['art', 'bot', 'bsm', 'cmp', 'crc', 'crs', 'dim', 'g4', 'gb0', 'gb1', 'gb2', 'gb3', 'gb5',
  1202. 'gb6', 'gb7', 'gb8', 'gb9', 'gbd', 'gbl', 'gbo', 'gbp', 'gbr', 'gbs', 'gdo', 'ger', 'gko',
  1203. 'gml', 'gm1', 'gm2', 'gm3', 'grb', 'gtl', 'gto', 'gtp', 'gts', 'ly15', 'ly2', 'mil', 'outline',
  1204. 'pho', 'plc', 'pls', 'smb', 'smt', 'sol', 'spb', 'spt', 'ssb', 'sst', 'stc', 'sts', 'top',
  1205. 'tsm']
  1206. self.exc_list = ['drd', 'drl', 'drill', 'exc', 'ncd', 'tap', 'txt', 'xln']
  1207. self.gcode_list = ['cnc', 'din', 'dnc', 'ecs', 'eia', 'fan', 'fgc', 'fnc', 'gc', 'gcd', 'gcode', 'h', 'hnc',
  1208. 'i', 'min', 'mpf', 'mpr', 'nc', 'ncc', 'ncg', 'ngc', 'ncp', 'out', 'ply', 'rol',
  1209. 'sbp', 'tap', 'xpi']
  1210. self.svg_list = ['svg']
  1211. self.dxf_list = ['dxf']
  1212. self.pdf_list = ['pdf']
  1213. self.prj_list = ['flatprj']
  1214. self.conf_list = ['flatconfig']
  1215. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1216. # flag for polygons not cleared
  1217. self.poly_not_cleared = False
  1218. # VisPy visuals
  1219. self.isHovering = False
  1220. self.notHovering = True
  1221. # Window geometry
  1222. self.x_pos = None
  1223. self.y_pos = None
  1224. self.width = None
  1225. self.height = None
  1226. # when True, the app has to return from any thread
  1227. self.abort_flag = False
  1228. # set the value used in the Windows Title
  1229. self.engine = self.ui.general_defaults_form.general_app_group.ge_radio.get_value()
  1230. # this holds a widget that is installed in the Plot Area when View Source option is used
  1231. self.source_editor_tab = None
  1232. self.pagesize = {}
  1233. # Storage for shapes, storage that can be used by FlatCAm tools for utility geometry
  1234. # VisPy visuals
  1235. if self.is_legacy is False:
  1236. try:
  1237. self.tool_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  1238. except AttributeError:
  1239. self.tool_shapes = None
  1240. else:
  1241. from AppGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  1242. self.tool_shapes = ShapeCollectionLegacy(obj=self, app=self, name="tool")
  1243. # used in the delayed shutdown self.start_delayed_quit() method
  1244. self.save_timer = None
  1245. # ###########################################################################################################
  1246. # ################################## ADDING FlatCAM EDITORS section #########################################
  1247. # ###########################################################################################################
  1248. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  1249. # at the first launch of the App , the editors will not be functional.
  1250. try:
  1251. self.geo_editor = FlatCAMGeoEditor(self)
  1252. except AttributeError:
  1253. pass
  1254. try:
  1255. self.exc_editor = FlatCAMExcEditor(self)
  1256. except AttributeError:
  1257. pass
  1258. try:
  1259. self.grb_editor = FlatCAMGrbEditor(self)
  1260. except AttributeError:
  1261. pass
  1262. self.log.debug("Finished adding FlatCAM Editor's.")
  1263. self.set_ui_title(name=_("New Project - Not saved"))
  1264. # disable the Excellon path optimizations made with Google OR-Tools if the app is run on a 32bit platform
  1265. current_platform = platform.architecture()[0]
  1266. if current_platform != '64bit':
  1267. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T')
  1268. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.setDisabled(True)
  1269. # ###########################################################################################################
  1270. # ########################################### EXCLUSION AREAS ###############################################
  1271. # ###########################################################################################################
  1272. self.exc_areas = ExclusionAreas(app=self)
  1273. # ###########################################################################################################
  1274. # ##################################### Finished the CONSTRUCTOR ############################################
  1275. # ###########################################################################################################
  1276. App.log.debug("END of constructor. Releasing control.")
  1277. # ###########################################################################################################
  1278. # ########################################## SHOW GUI #######################################################
  1279. # ###########################################################################################################
  1280. # if the app is not started as headless, show it
  1281. if self.cmd_line_headless != 1:
  1282. if show_splash:
  1283. # finish the splash
  1284. self.splash.finish(self.ui)
  1285. mgui_settings = QSettings("Open Source", "FlatCAM")
  1286. if mgui_settings.contains("maximized_gui"):
  1287. maximized_ui = mgui_settings.value('maximized_gui', type=bool)
  1288. if maximized_ui is True:
  1289. self.ui.showMaximized()
  1290. else:
  1291. self.ui.show()
  1292. else:
  1293. self.ui.show()
  1294. if self.defaults["global_systray_icon"]:
  1295. self.trayIcon.show()
  1296. else:
  1297. log.warning("******************* RUNNING HEADLESS *******************")
  1298. # ###########################################################################################################
  1299. # ######################################## START-UP ARGUMENTS ###############################################
  1300. # ###########################################################################################################
  1301. # test if the program was started with a script as parameter
  1302. if self.cmd_line_shellvar:
  1303. try:
  1304. cnt = 0
  1305. command_tcl = 0
  1306. for i in self.cmd_line_shellvar.split(','):
  1307. if i is not None:
  1308. # noinspection PyBroadException
  1309. try:
  1310. command_tcl = eval(i)
  1311. except Exception:
  1312. command_tcl = i
  1313. command_tcl_formatted = 'set shellvar_{nr} "{cmd}"'.format(cmd=str(command_tcl), nr=str(cnt))
  1314. cnt += 1
  1315. # if there are Windows paths then replace the path separator with a Unix like one
  1316. if sys.platform == 'win32':
  1317. command_tcl_formatted = command_tcl_formatted.replace('\\', '/')
  1318. self.shell.exec_command(command_tcl_formatted, no_echo=True)
  1319. except Exception as ext:
  1320. print("ERROR: ", ext)
  1321. sys.exit(2)
  1322. if self.cmd_line_shellfile:
  1323. if self.cmd_line_headless != 1:
  1324. if self.ui.shell_dock.isHidden():
  1325. self.ui.shell_dock.show()
  1326. try:
  1327. with open(self.cmd_line_shellfile, "r") as myfile:
  1328. # if show_splash:
  1329. # self.splash.showMessage('%s: %ssec\n%s' % (
  1330. # _("Canvas initialization started.\n"
  1331. # "Canvas initialization finished in"), '%.2f' % self.used_time,
  1332. # _("Executing Tcl Script ...")),
  1333. # alignment=Qt.AlignBottom | Qt.AlignLeft,
  1334. # color=QtGui.QColor("gray"))
  1335. cmd_line_shellfile_text = myfile.read()
  1336. if self.cmd_line_headless != 1:
  1337. self.shell.exec_command(cmd_line_shellfile_text)
  1338. else:
  1339. self.shell.exec_command(cmd_line_shellfile_text, no_echo=True)
  1340. except Exception as ext:
  1341. print("ERROR: ", ext)
  1342. sys.exit(2)
  1343. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  1344. # the path/file_name must be enclosed in quotes if it contain spaces
  1345. if App.args:
  1346. self.args_at_startup.emit(App.args)
  1347. if self.defaults.old_defaults_found is True:
  1348. self.inform.emit('[WARNING_NOTCL] %s' % _("Found old default preferences files. "
  1349. "Please reboot the application to update."))
  1350. self.defaults.old_defaults_found = False
  1351. # ######################################### INIT FINISHED #######################################################
  1352. # #################################################################################################################
  1353. # #################################################################################################################
  1354. # #################################################################################################################
  1355. # #################################################################################################################
  1356. # #################################################################################################################
  1357. @staticmethod
  1358. def copy_and_overwrite(from_path, to_path):
  1359. """
  1360. From here:
  1361. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  1362. :param from_path: source path
  1363. :param to_path: destination path
  1364. :return: None
  1365. """
  1366. if os.path.exists(to_path):
  1367. shutil.rmtree(to_path)
  1368. try:
  1369. shutil.copytree(from_path, to_path)
  1370. except FileNotFoundError:
  1371. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\AppGUI\\VisPyData\\data'
  1372. shutil.copytree(from_new_path, to_path)
  1373. def on_startup_args(self, args, silent=False):
  1374. """
  1375. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  1376. :param silent: when True it will not print messages on Tcl Shell and/or status bar
  1377. :param args: a list containing the application args at startup
  1378. :return: None
  1379. """
  1380. if args is not None:
  1381. args_to_process = args
  1382. else:
  1383. args_to_process = App.args
  1384. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  1385. for argument in args_to_process:
  1386. if '.FlatPrj'.lower() in argument.lower():
  1387. try:
  1388. project_name = str(argument)
  1389. if project_name == "":
  1390. if silent is False:
  1391. self.inform.emit(_("Cancelled."))
  1392. else:
  1393. # self.open_project(project_name)
  1394. run_from_arg = True
  1395. # self.worker_task.emit({'fcn': self.open_project,
  1396. # 'params': [project_name, run_from_arg]})
  1397. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  1398. except Exception as e:
  1399. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  1400. elif '.FlatConfig'.lower() in argument.lower():
  1401. try:
  1402. file_name = str(argument)
  1403. if file_name == "":
  1404. if silent is False:
  1405. self.inform.emit(_("Open Config file failed."))
  1406. else:
  1407. run_from_arg = True
  1408. # self.worker_task.emit({'fcn': self.open_config_file,
  1409. # 'params': [file_name, run_from_arg]})
  1410. self.open_config_file(file_name, run_from_arg=run_from_arg)
  1411. except Exception as e:
  1412. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  1413. elif '.FlatScript'.lower() in argument.lower() or '.TCL'.lower() in argument.lower():
  1414. try:
  1415. file_name = str(argument)
  1416. if file_name == "":
  1417. if silent is False:
  1418. self.inform.emit(_("Open Script file failed."))
  1419. else:
  1420. if silent is False:
  1421. self.on_fileopenscript(name=file_name)
  1422. self.ui.plot_tab_area.setCurrentWidget(self.ui.plot_tab)
  1423. self.on_filerunscript(name=file_name)
  1424. except Exception as e:
  1425. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  1426. elif 'quit'.lower() in argument.lower() or 'exit'.lower() in argument.lower():
  1427. log.debug("App.on_startup_args() --> Quit event.")
  1428. sys.exit()
  1429. elif 'save'.lower() in argument.lower():
  1430. log.debug("App.on_startup_args() --> Save event. App Defaults saved.")
  1431. self.preferencesUiManager.save_defaults()
  1432. else:
  1433. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  1434. proc_arg = argument.lower()
  1435. for ext in exc_list:
  1436. proc_ext = ext.replace(' ', '')
  1437. proc_ext = '.%s' % proc_ext
  1438. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1439. file_name = str(argument)
  1440. if file_name == "":
  1441. if silent is False:
  1442. self.inform.emit(_("Open Excellon file failed."))
  1443. else:
  1444. self.on_fileopenexcellon(name=file_name, signal=None)
  1445. return
  1446. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  1447. for ext in gco_list:
  1448. proc_ext = ext.replace(' ', '')
  1449. proc_ext = '.%s' % proc_ext
  1450. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1451. file_name = str(argument)
  1452. if file_name == "":
  1453. if silent is False:
  1454. self.inform.emit(_("Open GCode file failed."))
  1455. else:
  1456. self.on_fileopengcode(name=file_name, signal=None)
  1457. return
  1458. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  1459. for ext in grb_list:
  1460. proc_ext = ext.replace(' ', '')
  1461. proc_ext = '.%s' % proc_ext
  1462. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1463. file_name = str(argument)
  1464. if file_name == "":
  1465. if silent is False:
  1466. self.inform.emit(_("Open Gerber file failed."))
  1467. else:
  1468. self.on_fileopengerber(name=file_name, signal=None)
  1469. return
  1470. # if it reached here without already returning then the app was registered with a file that it does not
  1471. # recognize therefore we must quit but take into consideration the app reboot from within, in that case
  1472. # the args_to_process will contain the path to the FlatCAM.exe (cx_freezed executable)
  1473. # for arg in args_to_process:
  1474. # if 'FlatCAM.exe' in arg:
  1475. # continue
  1476. # else:
  1477. # sys.exit(2)
  1478. def set_ui_title(self, name):
  1479. """
  1480. Sets the title of the main window.
  1481. :param name: String that store the project path and project name
  1482. :return: None
  1483. """
  1484. self.ui.setWindowTitle('FlatCAM %s %s - %s - [%s] %s' %
  1485. (self.version,
  1486. ('BETA' if self.beta else ''),
  1487. platform.architecture()[0],
  1488. self.engine,
  1489. name)
  1490. )
  1491. def on_app_restart(self):
  1492. # make sure that the Sys Tray icon is hidden before restart otherwise it will
  1493. # be left in the SySTray
  1494. try:
  1495. self.trayIcon.hide()
  1496. except Exception:
  1497. pass
  1498. fcTranslate.restart_program(app=self)
  1499. def clear_pool(self):
  1500. """
  1501. Clear the multiprocessing pool and calls garbage collector.
  1502. :return: None
  1503. """
  1504. self.pool.close()
  1505. self.pool = Pool()
  1506. self.pool_recreated.emit(self.pool)
  1507. gc.collect()
  1508. def install_tools(self):
  1509. """
  1510. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  1511. Instantiation of the Tools classes.
  1512. The order that the tools are installed is important as they can depend on each other install position.
  1513. :return: None
  1514. """
  1515. self.distance_tool = Distance(self)
  1516. self.distance_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance16.png'), pos=self.ui.menuedit,
  1517. before=self.ui.menueditorigin,
  1518. separator=False)
  1519. self.distance_min_tool = DistanceMin(self)
  1520. self.distance_min_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance_min16.png'),
  1521. pos=self.ui.menuedit,
  1522. before=self.ui.menueditorigin,
  1523. separator=True)
  1524. self.dblsidedtool = DblSidedTool(self)
  1525. self.dblsidedtool.install(icon=QtGui.QIcon(self.resource_location + '/doubleside16.png'), separator=False)
  1526. self.cal_exc_tool = ToolCalibration(self)
  1527. self.cal_exc_tool.install(icon=QtGui.QIcon(self.resource_location + '/calibrate_16.png'), pos=self.ui.menutool,
  1528. before=self.dblsidedtool.menuAction,
  1529. separator=False)
  1530. self.align_objects_tool = AlignObjects(self)
  1531. self.align_objects_tool.install(icon=QtGui.QIcon(self.resource_location + '/align16.png'), separator=False)
  1532. self.edrills_tool = ToolExtractDrills(self)
  1533. self.edrills_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill16.png'), separator=True)
  1534. self.panelize_tool = Panelize(self)
  1535. self.panelize_tool.install(icon=QtGui.QIcon(self.resource_location + '/panelize16.png'))
  1536. self.film_tool = Film(self)
  1537. self.film_tool.install(icon=QtGui.QIcon(self.resource_location + '/film16.png'))
  1538. self.paste_tool = SolderPaste(self)
  1539. self.paste_tool.install(icon=QtGui.QIcon(self.resource_location + '/solderpastebis32.png'))
  1540. self.calculator_tool = ToolCalculator(self)
  1541. self.calculator_tool.install(icon=QtGui.QIcon(self.resource_location + '/calculator16.png'), separator=True)
  1542. self.sub_tool = ToolSub(self)
  1543. self.sub_tool.install(icon=QtGui.QIcon(self.resource_location + '/sub32.png'),
  1544. pos=self.ui.menutool, separator=True)
  1545. self.rules_tool = RulesCheck(self)
  1546. self.rules_tool.install(icon=QtGui.QIcon(self.resource_location + '/rules32.png'),
  1547. pos=self.ui.menutool, separator=False)
  1548. self.optimal_tool = ToolOptimal(self)
  1549. self.optimal_tool.install(icon=QtGui.QIcon(self.resource_location + '/open_excellon32.png'),
  1550. pos=self.ui.menutool, separator=True)
  1551. self.move_tool = ToolMove(self)
  1552. self.move_tool.install(icon=QtGui.QIcon(self.resource_location + '/move16.png'), pos=self.ui.menuedit,
  1553. before=self.ui.menueditorigin, separator=True)
  1554. self.cutout_tool = CutOut(self)
  1555. self.cutout_tool.install(icon=QtGui.QIcon(self.resource_location + '/cut16_bis.png'), pos=self.ui.menutool,
  1556. before=self.sub_tool.menuAction)
  1557. self.ncclear_tool = NonCopperClear(self)
  1558. self.ncclear_tool.install(icon=QtGui.QIcon(self.resource_location + '/ncc16.png'), pos=self.ui.menutool,
  1559. before=self.sub_tool.menuAction, separator=True)
  1560. self.paint_tool = ToolPaint(self)
  1561. self.paint_tool.install(icon=QtGui.QIcon(self.resource_location + '/paint16.png'), pos=self.ui.menutool,
  1562. before=self.sub_tool.menuAction, separator=True)
  1563. self.isolation_tool = ToolIsolation(self)
  1564. self.isolation_tool.install(icon=QtGui.QIcon(self.resource_location + '/iso_16.png'), pos=self.ui.menutool,
  1565. before=self.sub_tool.menuAction, separator=True)
  1566. self.copper_thieving_tool = ToolCopperThieving(self)
  1567. self.copper_thieving_tool.install(icon=QtGui.QIcon(self.resource_location + '/copperfill32.png'),
  1568. pos=self.ui.menutool)
  1569. self.fiducial_tool = ToolFiducials(self)
  1570. self.fiducial_tool.install(icon=QtGui.QIcon(self.resource_location + '/fiducials_32.png'),
  1571. pos=self.ui.menutool)
  1572. self.qrcode_tool = QRCode(self)
  1573. self.qrcode_tool.install(icon=QtGui.QIcon(self.resource_location + '/qrcode32.png'),
  1574. pos=self.ui.menutool)
  1575. self.punch_tool = ToolPunchGerber(self)
  1576. self.punch_tool.install(icon=QtGui.QIcon(self.resource_location + '/punch32.png'), pos=self.ui.menutool)
  1577. self.invert_tool = ToolInvertGerber(self)
  1578. self.invert_tool.install(icon=QtGui.QIcon(self.resource_location + '/invert32.png'), pos=self.ui.menutool)
  1579. self.corners_tool = ToolCorners(self)
  1580. self.corners_tool.install(icon=QtGui.QIcon(self.resource_location + '/corners_32.png'), pos=self.ui.menutool)
  1581. self.etch_tool = ToolEtchCompensation(self)
  1582. self.etch_tool.install(icon=QtGui.QIcon(self.resource_location + '/etch_32.png'), pos=self.ui.menutool)
  1583. self.transform_tool = ToolTransform(self)
  1584. self.transform_tool.install(icon=QtGui.QIcon(self.resource_location + '/transform.png'),
  1585. pos=self.ui.menuoptions, separator=True)
  1586. self.properties_tool = Properties(self)
  1587. self.properties_tool.install(icon=QtGui.QIcon(self.resource_location + '/properties32.png'),
  1588. pos=self.ui.menuoptions)
  1589. self.pdf_tool = ToolPDF(self)
  1590. self.pdf_tool.install(icon=QtGui.QIcon(self.resource_location + '/pdf32.png'),
  1591. pos=self.ui.menufileimport,
  1592. separator=True)
  1593. self.image_tool = ToolImage(self)
  1594. self.image_tool.install(icon=QtGui.QIcon(self.resource_location + '/image32.png'),
  1595. pos=self.ui.menufileimport,
  1596. separator=True)
  1597. self.pcb_wizard_tool = PcbWizard(self)
  1598. self.pcb_wizard_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill32.png'),
  1599. pos=self.ui.menufileimport)
  1600. self.log.debug("Tools are installed.")
  1601. def remove_tools(self):
  1602. """
  1603. Will remove all the actions in the Tool menu.
  1604. :return: None
  1605. """
  1606. for act in self.ui.menutool.actions():
  1607. self.ui.menutool.removeAction(act)
  1608. def init_tools(self):
  1609. """
  1610. Initialize the Tool tab in the notebook side of the central widget.
  1611. Remove the actions in the Tools menu.
  1612. Instantiate again the FlatCAM tools (plugins).
  1613. All this is required when changing the layout: standard, compact etc.
  1614. :return: None
  1615. """
  1616. log.debug("init_tools()")
  1617. # delete the data currently in the Tools Tab and the Tab itself
  1618. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  1619. if widget is not None:
  1620. widget.deleteLater()
  1621. self.ui.notebook.removeTab(2)
  1622. # rebuild the Tools Tab
  1623. self.ui.tool_tab = QtWidgets.QWidget()
  1624. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  1625. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  1626. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  1627. self.ui.tool_scroll_area = VerticalScrollArea()
  1628. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  1629. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  1630. # first remove all of them
  1631. self.remove_tools()
  1632. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  1633. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon(self.resource_location + '/shell16.png'),
  1634. '&Command Line\tS')
  1635. self.ui.menutoolshell.triggered.connect(self.ui.toggle_shell_ui)
  1636. # third install all of them
  1637. try:
  1638. self.install_tools()
  1639. except AttributeError:
  1640. pass
  1641. self.log.debug("Tools are initialized.")
  1642. # def parse_system_fonts(self):
  1643. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  1644. # 'params': []})
  1645. def connect_toolbar_signals(self):
  1646. """
  1647. Reconnect the signals to the actions in the toolbar.
  1648. This has to be done each time after the FlatCAM tools are removed/installed.
  1649. :return: None
  1650. """
  1651. # Toolbar
  1652. # File Toolbar Signals
  1653. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  1654. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  1655. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  1656. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  1657. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  1658. # View Toolbar Signals
  1659. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  1660. self.ui.replot_btn.triggered.connect(self.plot_all)
  1661. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  1662. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  1663. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  1664. # Edit Toolbar Signals
  1665. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  1666. self.ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  1667. self.ui.copy_btn.triggered.connect(self.on_copy_command)
  1668. self.ui.delete_btn.triggered.connect(self.on_delete)
  1669. self.ui.distance_btn.triggered.connect(lambda: self.distance_tool.run(toggle=True))
  1670. self.ui.distance_min_btn.triggered.connect(lambda: self.distance_min_tool.run(toggle=True))
  1671. self.ui.origin_btn.triggered.connect(self.on_set_origin)
  1672. self.ui.move2origin_btn.triggered.connect(self.on_move2origin)
  1673. self.ui.jmp_btn.triggered.connect(self.on_jump_to)
  1674. self.ui.locate_btn.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  1675. # Scripting Toolbar Signals
  1676. self.ui.shell_btn.triggered.connect(self.ui.toggle_shell_ui)
  1677. self.ui.new_script_btn.triggered.connect(self.on_filenewscript)
  1678. self.ui.open_script_btn.triggered.connect(self.on_fileopenscript)
  1679. self.ui.run_script_btn.triggered.connect(self.on_filerunscript)
  1680. # Tools Toolbar Signals
  1681. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  1682. self.ui.cal_btn.triggered.connect(lambda: self.cal_exc_tool.run(toggle=True))
  1683. self.ui.align_btn.triggered.connect(lambda: self.align_objects_tool.run(toggle=True))
  1684. self.ui.extract_btn.triggered.connect(lambda: self.edrills_tool.run(toggle=True))
  1685. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  1686. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  1687. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  1688. self.ui.isolation_btn.triggered.connect(lambda: self.isolation_tool.run(toggle=True))
  1689. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  1690. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  1691. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  1692. self.ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  1693. self.ui.rules_btn.triggered.connect(lambda: self.rules_tool.run(toggle=True))
  1694. self.ui.optimal_btn.triggered.connect(lambda: self.optimal_tool.run(toggle=True))
  1695. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  1696. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  1697. self.ui.qrcode_btn.triggered.connect(lambda: self.qrcode_tool.run(toggle=True))
  1698. self.ui.copperfill_btn.triggered.connect(lambda: self.copper_thieving_tool.run(toggle=True))
  1699. self.ui.fiducials_btn.triggered.connect(lambda: self.fiducial_tool.run(toggle=True))
  1700. self.ui.punch_btn.triggered.connect(lambda: self.punch_tool.run(toggle=True))
  1701. self.ui.invert_btn.triggered.connect(lambda: self.invert_tool.run(toggle=True))
  1702. self.ui.corners_tool_btn.triggered.connect(lambda: self.corners_tool.run(toggle=True))
  1703. self.ui.etch_btn.triggered.connect(lambda: self.etch_tool.run(toggle=True))
  1704. def object2editor(self):
  1705. """
  1706. Send the current Geometry, Gerber, Excellon object or CNCJob (if any) into the it's editor.
  1707. :return: None
  1708. """
  1709. self.defaults.report_usage("object2editor()")
  1710. # disable the objects menu as it may interfere with the AppEditors
  1711. self.ui.menuobjects.setDisabled(True)
  1712. edited_object = self.collection.get_active()
  1713. if isinstance(edited_object, GerberObject) or isinstance(edited_object, GeometryObject) or \
  1714. isinstance(edited_object, ExcellonObject) or isinstance(edited_object, CNCJobObject):
  1715. pass
  1716. else:
  1717. self.inform.emit('[WARNING_NOTCL] %s' % _("Select a Geometry, Gerber, Excellon or CNCJob Object to edit."))
  1718. return
  1719. if isinstance(edited_object, GeometryObject):
  1720. # store the Geometry Editor Toolbar visibility before entering in the Editor
  1721. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  1722. # we set the notebook to hidden
  1723. # self.ui.splitter.setSizes([0, 1])
  1724. if edited_object.multigeo is True:
  1725. sel_rows = [item.row() for item in edited_object.ui.geo_tools_table.selectedItems()]
  1726. if len(sel_rows) > 1:
  1727. self.inform.emit('[WARNING_NOTCL] %s' %
  1728. _("Simultaneous editing of tools geometry in a MultiGeo Geometry "
  1729. "is not possible.\n"
  1730. "Edit only one geometry at a time."))
  1731. # determine the tool dia of the selected tool
  1732. selected_tooldia = float(edited_object.ui.geo_tools_table.item(sel_rows[0], 1).text())
  1733. # now find the key in the edited_object.tools that has this tooldia
  1734. multi_tool = 1
  1735. for tool in edited_object.tools:
  1736. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  1737. multi_tool = tool
  1738. break
  1739. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  1740. else:
  1741. self.geo_editor.edit_fcgeometry(edited_object)
  1742. # set call source to the Editor we go into
  1743. self.call_source = 'geo_editor'
  1744. elif isinstance(edited_object, ExcellonObject):
  1745. # store the Excellon Editor Toolbar visibility before entering in the Editor
  1746. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  1747. if self.ui.splitter.sizes()[0] == 0:
  1748. self.ui.splitter.setSizes([1, 1])
  1749. self.exc_editor.edit_fcexcellon(edited_object)
  1750. # set call source to the Editor we go into
  1751. self.call_source = 'exc_editor'
  1752. elif isinstance(edited_object, GerberObject):
  1753. # store the Gerber Editor Toolbar visibility before entering in the Editor
  1754. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  1755. if self.ui.splitter.sizes()[0] == 0:
  1756. self.ui.splitter.setSizes([1, 1])
  1757. self.grb_editor.edit_fcgerber(edited_object)
  1758. # set call source to the Editor we go into
  1759. self.call_source = 'grb_editor'
  1760. # reset the following variables so the UI is built again after edit
  1761. edited_object.ui_build = False
  1762. edited_object.build_aperture_storage = False
  1763. elif isinstance(edited_object, CNCJobObject):
  1764. if self.ui.splitter.sizes()[0] == 0:
  1765. self.ui.splitter.setSizes([1, 1])
  1766. edited_object.on_edit_code_click()
  1767. return
  1768. # make sure that we can't select another object while in Editor Mode:
  1769. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  1770. self.ui.project_frame.setDisabled(True)
  1771. # delete any selection shape that might be active as they are not relevant in Editor
  1772. self.delete_selection_shape()
  1773. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  1774. self.ui.plot_tab_area.protectTab(0)
  1775. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor is activated ..."))
  1776. self.should_we_save = True
  1777. def editor2object(self, cleanup=None):
  1778. """
  1779. Transfers the Geometry or Excellon from it's editor to the current object.
  1780. :return: None
  1781. """
  1782. self.defaults.report_usage("editor2object()")
  1783. # re-enable the objects menu that was disabled on entry in Editor mode
  1784. self.ui.menuobjects.setDisabled(False)
  1785. # do not update a geometry or excellon object unless it comes out of an editor
  1786. if self.call_source != 'app':
  1787. edited_obj = self.collection.get_active()
  1788. if cleanup is None:
  1789. msgbox = QtWidgets.QMessageBox()
  1790. msgbox.setText(_("Do you want to save the edited object?"))
  1791. msgbox.setWindowTitle(_("Close Editor"))
  1792. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  1793. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  1794. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  1795. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  1796. msgbox.setDefaultButton(bt_yes)
  1797. msgbox.exec_()
  1798. response = msgbox.clickedButton()
  1799. if response == bt_yes:
  1800. # clean the Tools Tab
  1801. self.ui.tool_scroll_area.takeWidget()
  1802. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1803. self.ui.notebook.setTabText(2, "Tool")
  1804. if isinstance(edited_obj, GeometryObject):
  1805. obj_type = "Geometry"
  1806. self.geo_editor.update_fcgeometry(edited_obj)
  1807. # self.geo_editor.update_options(edited_obj)
  1808. # restore GUI to the Selected TAB
  1809. # Remove anything else in the AppGUI
  1810. self.ui.tool_scroll_area.takeWidget()
  1811. # update the geo object options so it is including the bounding box values
  1812. try:
  1813. xmin, ymin, xmax, ymax = edited_obj.bounds(flatten=True)
  1814. edited_obj.options['xmin'] = xmin
  1815. edited_obj.options['ymin'] = ymin
  1816. edited_obj.options['xmax'] = xmax
  1817. edited_obj.options['ymax'] = ymax
  1818. except AttributeError as e:
  1819. self.inform.emit('[WARNING] %s' % _("Object empty after edit."))
  1820. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  1821. edited_obj.build_ui()
  1822. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1823. elif isinstance(edited_obj, GerberObject):
  1824. obj_type = "Gerber"
  1825. self.grb_editor.update_fcgerber()
  1826. # self.grb_editor.update_options(edited_obj)
  1827. # delete the old object (the source object) if it was an empty one
  1828. try:
  1829. if len(edited_obj.solid_geometry) == 0:
  1830. old_name = edited_obj.options['name']
  1831. self.collection.delete_by_name(old_name)
  1832. except TypeError:
  1833. # if the solid_geometry is a single Polygon the len() will not work
  1834. # in any case, falling here means that we have something in the solid_geometry, even if only
  1835. # a single Polygon, therefore we pass this
  1836. pass
  1837. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1838. # restore GUI to the Selected TAB
  1839. # Remove anything else in the AppGUI
  1840. self.ui.selected_scroll_area.takeWidget()
  1841. elif isinstance(edited_obj, ExcellonObject):
  1842. obj_type = "Excellon"
  1843. self.exc_editor.update_fcexcellon(edited_obj)
  1844. # self.exc_editor.update_options(edited_obj)
  1845. # restore GUI to the Selected TAB
  1846. # Remove anything else in the AppGUI
  1847. self.ui.tool_scroll_area.takeWidget()
  1848. # delete the old object (the source object) if it was an empty one
  1849. if len(edited_obj.drills) == 0 and len(edited_obj.slots) == 0:
  1850. old_name = edited_obj.options['name']
  1851. self.collection.delete_by_name(name=old_name)
  1852. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1853. else:
  1854. self.inform.emit('[WARNING_NOTCL] %s' %
  1855. _("Select a Gerber, Geometry or Excellon Object to update."))
  1856. return
  1857. self.inform.emit('[selected] %s %s' % (obj_type, _("is updated, returning to App...")))
  1858. elif response == bt_no:
  1859. # clean the Tools Tab
  1860. self.ui.tool_scroll_area.takeWidget()
  1861. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1862. self.ui.notebook.setTabText(2, "Tool")
  1863. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor exited. Editor content was not saved."))
  1864. if isinstance(edited_obj, GeometryObject):
  1865. self.geo_editor.deactivate()
  1866. edited_obj.build_ui()
  1867. elif isinstance(edited_obj, GerberObject):
  1868. self.grb_editor.deactivate_grb_editor()
  1869. edited_obj.build_ui()
  1870. elif isinstance(edited_obj, ExcellonObject):
  1871. self.exc_editor.deactivate()
  1872. edited_obj.build_ui()
  1873. else:
  1874. self.inform.emit('[WARNING_NOTCL] %s' %
  1875. _("Select a Gerber, Geometry or Excellon Object to update."))
  1876. return
  1877. elif response == bt_cancel:
  1878. return
  1879. # edited_obj.set_ui(edited_obj.ui_type(decimals=self.decimals))
  1880. # edited_obj.build_ui()
  1881. # Switch notebook to Selected page
  1882. # self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  1883. else:
  1884. if isinstance(edited_obj, GeometryObject):
  1885. self.geo_editor.deactivate()
  1886. elif isinstance(edited_obj, GerberObject):
  1887. self.grb_editor.deactivate_grb_editor()
  1888. elif isinstance(edited_obj, ExcellonObject):
  1889. self.exc_editor.deactivate()
  1890. else:
  1891. self.inform.emit('[WARNING_NOTCL] %s' %
  1892. _("Select a Gerber, Geometry or Excellon Object to update."))
  1893. return
  1894. # if notebook is hidden we show it
  1895. if self.ui.splitter.sizes()[0] == 0:
  1896. self.ui.splitter.setSizes([1, 1])
  1897. # restore the call_source to app
  1898. self.call_source = 'app'
  1899. # edited_obj.plot()
  1900. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  1901. self.ui.plot_tab_area.protectTab(0)
  1902. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  1903. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  1904. self.ui.project_frame.setDisabled(False)
  1905. def get_last_folder(self):
  1906. """
  1907. Get the folder path from where the last file was opened.
  1908. :return: String, last opened folder path
  1909. """
  1910. return self.defaults["global_last_folder"]
  1911. def get_last_save_folder(self):
  1912. """
  1913. Get the folder path from where the last file was saved.
  1914. :return: String, last saved folder path
  1915. """
  1916. loc = self.defaults["global_last_save_folder"]
  1917. if loc is None:
  1918. loc = self.defaults["global_last_folder"]
  1919. if loc is None:
  1920. loc = os.path.dirname(__file__)
  1921. return loc
  1922. def info(self, msg):
  1923. """
  1924. Informs the user. Normally on the status bar, optionally
  1925. also on the shell.
  1926. :param msg: Text to write.
  1927. :return: None
  1928. """
  1929. # Type of message in brackets at the beginning of the message.
  1930. match = re.search(r"\[(.*)\](.*)", msg)
  1931. if match:
  1932. level = match.group(1)
  1933. msg_ = match.group(2)
  1934. self.ui.fcinfo.set_status(str(msg_), level=level)
  1935. if level.lower() == "error":
  1936. self.shell_message(msg, error=True, show=True)
  1937. elif level.lower() == "warning":
  1938. self.shell_message(msg, warning=True, show=True)
  1939. elif level.lower() == "error_notcl":
  1940. self.shell_message(msg, error=True, show=False)
  1941. elif level.lower() == "warning_notcl":
  1942. self.shell_message(msg, warning=True, show=False)
  1943. elif level.lower() == "success":
  1944. self.shell_message(msg, success=True, show=False)
  1945. elif level.lower() == "selected":
  1946. self.shell_message(msg, selected=True, show=False)
  1947. else:
  1948. self.shell_message(msg, show=False)
  1949. else:
  1950. self.ui.fcinfo.set_status(str(msg), level="info")
  1951. # make sure that if the message is to clear the infobar with a space
  1952. # is not printed over and over on the shell
  1953. if msg != '':
  1954. self.shell_message(msg)
  1955. def on_import_preferences(self):
  1956. """
  1957. Loads the application default settings from a saved file into
  1958. ``self.defaults`` dictionary.
  1959. :return: None
  1960. """
  1961. self.defaults.report_usage("on_import_preferences")
  1962. App.log.debug("App.on_import_preferences()")
  1963. # Show file chooser
  1964. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  1965. try:
  1966. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  1967. directory=self.data_path,
  1968. filter=filter_)
  1969. except TypeError:
  1970. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  1971. filter=filter_)
  1972. filename = str(filename)
  1973. if filename == "":
  1974. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  1975. return
  1976. # Load in the defaults from the chosen file
  1977. self.defaults.load(filename=filename)
  1978. self.preferencesUiManager.on_preferences_edited()
  1979. self.inform.emit('[success] %s: %s' % (_("Imported Defaults from"), filename))
  1980. def on_export_preferences(self):
  1981. """
  1982. Save the defaults dictionary to a file.
  1983. :return: None
  1984. """
  1985. self.defaults.report_usage("on_export_preferences")
  1986. App.log.debug("on_export_preferences()")
  1987. # defaults_file_content = None
  1988. # Show file chooser
  1989. date = str(datetime.today()).rpartition('.')[0]
  1990. date = ''.join(c for c in date if c not in ':-')
  1991. date = date.replace(' ', '_')
  1992. filter__ = "Config File .FlatConfig (*.FlatConfig);;All Files (*.*)"
  1993. try:
  1994. filename, _f = FCFileSaveDialog.get_saved_filename(
  1995. caption=_("Export FlatCAM Preferences"),
  1996. directory=self.data_path + '/preferences_' + date,
  1997. filter=filter__
  1998. )
  1999. except TypeError:
  2000. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export FlatCAM Preferences"), filter=filter__)
  2001. filename = str(filename)
  2002. if filename == "":
  2003. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2004. return
  2005. # Update options
  2006. self.preferencesUiManager.defaults_read_form()
  2007. self.defaults.propagate_defaults()
  2008. # Save update options
  2009. try:
  2010. self.defaults.write(filename=filename)
  2011. except Exception:
  2012. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2013. return
  2014. if self.defaults["global_open_style"] is False:
  2015. self.file_opened.emit("preferences", filename)
  2016. self.file_saved.emit("preferences", filename)
  2017. self.inform.emit('[success] %s: %s' % (_("Exported preferences to"), filename))
  2018. def save_to_file(self, content_to_save, txt_content):
  2019. """
  2020. Save something to a file.
  2021. :return: None
  2022. """
  2023. self.defaults.report_usage("save_to_file")
  2024. App.log.debug("save_to_file()")
  2025. self.date = str(datetime.today()).rpartition('.')[0]
  2026. self.date = ''.join(c for c in self.date if c not in ':-')
  2027. self.date = self.date.replace(' ', '_')
  2028. filter__ = "HTML File .html (*.html);;TXT File .txt (*.txt);;All Files (*.*)"
  2029. path_to_save = self.defaults["global_last_save_folder"] if \
  2030. self.defaults["global_last_save_folder"] is not None else self.data_path
  2031. try:
  2032. filename, _f = FCFileSaveDialog.get_saved_filename(
  2033. caption=_("Save to file"),
  2034. directory=path_to_save + '/file_' + self.date,
  2035. filter=filter__
  2036. )
  2037. except TypeError:
  2038. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save to file"), filter=filter__)
  2039. filename = str(filename)
  2040. if filename == "":
  2041. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2042. return
  2043. else:
  2044. try:
  2045. with open(filename, 'w') as f:
  2046. ___ = f.read()
  2047. except PermissionError:
  2048. self.inform.emit('[WARNING] %s' %
  2049. _("Permission denied, saving not possible.\n"
  2050. "Most likely another app is holding the file open and not accessible."))
  2051. return
  2052. except IOError:
  2053. App.log.debug('Creating a new file ...')
  2054. f = open(filename, 'w')
  2055. f.close()
  2056. except Exception:
  2057. e = sys.exc_info()[0]
  2058. App.log.error("Could not load the file.")
  2059. App.log.error(str(e))
  2060. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load the file."))
  2061. return
  2062. # Save content
  2063. if filename.rpartition('.')[2].lower() == 'html':
  2064. file_content = content_to_save
  2065. else:
  2066. file_content = txt_content
  2067. try:
  2068. with open(filename, "w") as f:
  2069. f.write(file_content)
  2070. except Exception:
  2071. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2072. return
  2073. self.inform.emit('[success] %s: %s' % (_("Exported file to"), filename))
  2074. def register_recent(self, kind, filename):
  2075. """
  2076. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  2077. dictionary.
  2078. :param kind: type of file that was opened
  2079. :param filename: the path and file name for the file that was opened
  2080. :return:
  2081. """
  2082. self.log.debug("register_recent()")
  2083. self.log.debug(" %s" % kind)
  2084. self.log.debug(" %s" % filename)
  2085. record = {'kind': str(kind), 'filename': str(filename)}
  2086. if record in self.recent:
  2087. return
  2088. if record in self.recent_projects:
  2089. return
  2090. if record['kind'] == 'project':
  2091. self.recent_projects.insert(0, record)
  2092. else:
  2093. self.recent.insert(0, record)
  2094. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  2095. self.recent.pop()
  2096. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  2097. self.recent_projects.pop()
  2098. try:
  2099. f = open(self.data_path + '/recent.json', 'w')
  2100. except IOError:
  2101. App.log.error("Failed to open recent items file for writing.")
  2102. self.inform.emit('[ERROR_NOTCL] %s' %
  2103. _('Failed to open recent files file for writing.'))
  2104. return
  2105. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  2106. f.close()
  2107. try:
  2108. fp = open(self.data_path + '/recent_projects.json', 'w')
  2109. except IOError:
  2110. App.log.error("Failed to open recent items file for writing.")
  2111. self.inform.emit('[ERROR_NOTCL] %s' %
  2112. _('Failed to open recent projects file for writing.'))
  2113. return
  2114. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  2115. fp.close()
  2116. # Re-build the recent items menu
  2117. self.setup_recent_items()
  2118. def on_about(self):
  2119. """
  2120. Displays the "about" dialog found in the Menu --> Help.
  2121. :return: None
  2122. """
  2123. self.defaults.report_usage("on_about")
  2124. version = self.version
  2125. version_date = self.version_date
  2126. beta = self.beta
  2127. class AboutDialog(QtWidgets.QDialog):
  2128. def __init__(self, app, parent=None):
  2129. QtWidgets.QDialog.__init__(self, parent)
  2130. self.app = app
  2131. # Icon and title
  2132. self.setWindowIcon(parent.app_icon)
  2133. self.setWindowTitle(_("About FlatCAM"))
  2134. self.resize(600, 200)
  2135. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  2136. # self.setStyleSheet(
  2137. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  2138. # "background-attachment: fixed"
  2139. # )
  2140. # bgimage = QtGui.QImage(self.resource_location + '/flatcam_icon256.png')
  2141. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  2142. # palette = QtGui.QPalette()
  2143. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  2144. # self.setPalette(palette)
  2145. logo = QtWidgets.QLabel()
  2146. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/flatcam_icon256.png'))
  2147. title = QtWidgets.QLabel(
  2148. "<font size=8><B>FlatCAM</B></font><BR>"
  2149. "{title}<BR>"
  2150. "<BR>"
  2151. "<BR>"
  2152. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  2153. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  2154. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">"
  2155. "<B>{issue}</B></a><BR>".format(
  2156. title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  2157. devel=_("Development"),
  2158. down=_("DOWNLOAD"),
  2159. issue=_("Issue tracker"))
  2160. )
  2161. title.setOpenExternalLinks(True)
  2162. closebtn = QtWidgets.QPushButton(_("Close"))
  2163. tab_widget = QtWidgets.QTabWidget()
  2164. description_label = QtWidgets.QLabel(
  2165. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  2166. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  2167. version=version,
  2168. beta=('BETA' if beta else ''),
  2169. date=version_date,
  2170. arch=platform.architecture()[0])
  2171. )
  2172. description_label.setOpenExternalLinks(True)
  2173. lic_lbl_header = QtWidgets.QLabel(
  2174. '%s:<br>%s<br>' % (
  2175. _('Licensed under the MIT license'),
  2176. "<a href = \"http://www.opensource.org/licenses/mit-license.php\">"
  2177. "http://www.opensource.org/licenses/mit-license.php</a>"
  2178. )
  2179. )
  2180. lic_lbl_header.setOpenExternalLinks(True)
  2181. lic_lbl_body = QtWidgets.QLabel(
  2182. _(
  2183. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  2184. 'of this software and associated documentation files (the "Software"), to deal\n'
  2185. 'in the Software without restriction, including without limitation the rights\n'
  2186. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  2187. 'copies of the Software, and to permit persons to whom the Software is\n'
  2188. 'furnished to do so, subject to the following conditions:\n\n'
  2189. 'The above copyright notice and this permission notice shall be included in\n'
  2190. 'all copies or substantial portions of the Software.\n\n'
  2191. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  2192. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  2193. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  2194. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  2195. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  2196. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  2197. 'THE SOFTWARE.'
  2198. )
  2199. )
  2200. attributions_label = QtWidgets.QLabel(
  2201. _(
  2202. 'Some of the icons used are from the following sources:<br>'
  2203. '<div>Icons by <a href="https://www.flaticon.com/authors/freepik" '
  2204. 'title="Freepik">Freepik</a> from <a href="https://www.flaticon.com/" '
  2205. 'title="Flaticon">www.flaticon.com</a></div>'
  2206. '<div>Icons by <a target="_blank" href="https://icons8.com">Icons8</a></div>'
  2207. 'Icons by <a href="http://www.onlinewebfonts.com">oNline Web Fonts</a>'
  2208. )
  2209. )
  2210. attributions_label.setOpenExternalLinks(True)
  2211. # layouts
  2212. layout1 = QtWidgets.QVBoxLayout()
  2213. layout1_1 = QtWidgets.QHBoxLayout()
  2214. layout1_2 = QtWidgets.QHBoxLayout()
  2215. layout2 = QtWidgets.QHBoxLayout()
  2216. layout3 = QtWidgets.QHBoxLayout()
  2217. self.setLayout(layout1)
  2218. layout1.addLayout(layout1_1)
  2219. layout1.addLayout(layout1_2)
  2220. layout1.addLayout(layout2)
  2221. layout1.addLayout(layout3)
  2222. layout1_1.addStretch()
  2223. layout1_1.addWidget(description_label)
  2224. layout1_2.addWidget(tab_widget)
  2225. self.splash_tab = QtWidgets.QWidget()
  2226. self.splash_tab.setObjectName("splash_about")
  2227. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  2228. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  2229. tab_widget.addTab(self.splash_tab, _("Splash"))
  2230. self.programmmers_tab = QtWidgets.QWidget()
  2231. self.programmmers_tab.setObjectName("programmers_about")
  2232. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  2233. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  2234. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  2235. self.translators_tab = QtWidgets.QWidget()
  2236. self.translators_tab.setObjectName("translators_about")
  2237. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  2238. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  2239. tab_widget.addTab(self.translators_tab, _("Translators"))
  2240. self.license_tab = QtWidgets.QWidget()
  2241. self.license_tab.setObjectName("license_about")
  2242. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  2243. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  2244. tab_widget.addTab(self.license_tab, _("License"))
  2245. self.attributions_tab = QtWidgets.QWidget()
  2246. self.attributions_tab.setObjectName("attributions_about")
  2247. self.attributions_tab_layout = QtWidgets.QVBoxLayout(self.attributions_tab)
  2248. self.attributions_tab_layout.setContentsMargins(2, 2, 2, 2)
  2249. tab_widget.addTab(self.attributions_tab, _("Attributions"))
  2250. self.splash_tab_layout.addWidget(logo, stretch=0)
  2251. self.splash_tab_layout.addWidget(title, stretch=1)
  2252. pal = QtGui.QPalette()
  2253. pal.setColor(QtGui.QPalette.Background, Qt.white)
  2254. self.prog_grid_lay = QtWidgets.QGridLayout()
  2255. self.prog_grid_lay.setHorizontalSpacing(20)
  2256. self.prog_grid_lay.setColumnStretch(0, 0)
  2257. self.prog_grid_lay.setColumnStretch(2, 1)
  2258. prog_widget = QtWidgets.QWidget()
  2259. prog_widget.setLayout(self.prog_grid_lay)
  2260. prog_scroll = QtWidgets.QScrollArea()
  2261. prog_scroll.setWidget(prog_widget)
  2262. prog_scroll.setWidgetResizable(True)
  2263. prog_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2264. prog_scroll.setPalette(pal)
  2265. self.programmmers_tab_layout.addWidget(prog_scroll)
  2266. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")), 0, 0)
  2267. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Status")), 0, 1)
  2268. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  2269. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Juan Pablo Caram"), 1, 0)
  2270. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("Program Author")), 1, 1)
  2271. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<>"), 1, 2)
  2272. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Denis Hayrullin"), 2, 0)
  2273. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Kamil Sopko"), 3, 0)
  2274. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 0)
  2275. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("BETA Maintainer >= 2019")), 4, 1)
  2276. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 2)
  2277. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 5, 0)
  2278. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "David Robertson"), 6, 0)
  2279. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Matthieu Berthomé"), 7, 0)
  2280. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Evans"), 8, 0)
  2281. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Victor Benso"), 9, 0)
  2282. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 10, 0)
  2283. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jørn Sandvik Nilsson"), 12, 0)
  2284. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lei Zheng"), 13, 0)
  2285. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Leandro Heck"), 14, 0)
  2286. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marco A Quezada"), 15, 0)
  2287. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 16, 0)
  2288. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Cedric Dussud"), 20, 0)
  2289. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Hemingway"), 22, 0)
  2290. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Damian Wrobel"), 24, 0)
  2291. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Daniel Sallin"), 28, 0)
  2292. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 32, 0)
  2293. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Bruno Vunderl"), 40, 0)
  2294. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Gonzalo Lopez"), 42, 0)
  2295. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jakob Staudt"), 45, 0)
  2296. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Smith"), 49, 0)
  2297. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 52, 0)
  2298. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Barnaby Walters"), 55, 0)
  2299. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Steve Martina"), 57, 0)
  2300. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Thomas Duffin"), 59, 0)
  2301. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 61, 0)
  2302. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 63, 0)
  2303. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Alex Lazar"), 64, 0)
  2304. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Breneman"), 65, 0)
  2305. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Eric Varsanyi"), 67, 0)
  2306. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lubos Medovarsky"), 69, 0)
  2307. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 74, 0)
  2308. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Idechix"), 100, 0)
  2309. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@SM"), 101, 0)
  2310. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@grbf"), 102, 0)
  2311. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Symonty"), 103, 0)
  2312. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@mgix"), 104, 0)
  2313. self.translator_grid_lay = QtWidgets.QGridLayout()
  2314. self.translator_grid_lay.setColumnStretch(0, 0)
  2315. self.translator_grid_lay.setColumnStretch(1, 0)
  2316. self.translator_grid_lay.setColumnStretch(2, 1)
  2317. self.translator_grid_lay.setColumnStretch(3, 0)
  2318. # trans_widget = QtWidgets.QWidget()
  2319. # trans_widget.setLayout(self.translator_grid_lay)
  2320. # self.translators_tab_layout.addWidget(trans_widget)
  2321. # self.translators_tab_layout.addStretch()
  2322. trans_widget = QtWidgets.QWidget()
  2323. trans_widget.setLayout(self.translator_grid_lay)
  2324. trans_scroll = QtWidgets.QScrollArea()
  2325. trans_scroll.setWidget(trans_widget)
  2326. trans_scroll.setWidgetResizable(True)
  2327. trans_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2328. trans_scroll.setPalette(pal)
  2329. self.translators_tab_layout.addWidget(trans_scroll)
  2330. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  2331. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  2332. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Corrections")), 0, 2)
  2333. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 3)
  2334. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "BR - Portuguese"), 1, 0)
  2335. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  2336. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<carlos.stein@gmail.com>"), 1, 3)
  2337. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "French"), 2, 0)
  2338. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 2, 1)
  2339. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 2, 2)
  2340. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 2, 3)
  2341. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Hungarian"), 3, 0)
  2342. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 1)
  2343. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 2)
  2344. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 3)
  2345. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Italian"), 4, 0)
  2346. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Golfetto Massimiliano"), 4, 1)
  2347. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 4, 2)
  2348. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<golfetto.pcb@gmail.com>"), 4, 3)
  2349. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 5, 0)
  2350. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 5, 1)
  2351. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jens Karstedt, Detlef Eckardt"), 5, 2)
  2352. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 5, 3)
  2353. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 6, 0)
  2354. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 6, 1)
  2355. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 6, 3)
  2356. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 7, 0)
  2357. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 7, 1)
  2358. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 7, 3)
  2359. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 8, 0)
  2360. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 8, 1)
  2361. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 8, 2)
  2362. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 8, 3)
  2363. self.translator_grid_lay.setColumnStretch(0, 0)
  2364. self.translators_tab_layout.addStretch()
  2365. self.license_tab_layout.addWidget(lic_lbl_header)
  2366. self.license_tab_layout.addWidget(lic_lbl_body)
  2367. self.license_tab_layout.addStretch()
  2368. self.attributions_tab_layout.addWidget(attributions_label)
  2369. self.attributions_tab_layout.addStretch()
  2370. layout3.addStretch()
  2371. layout3.addWidget(closebtn)
  2372. closebtn.clicked.connect(self.accept)
  2373. AboutDialog(app=self, parent=self.ui).exec_()
  2374. def install_bookmarks(self, book_dict=None):
  2375. """
  2376. Install the bookmarks actions in the Help menu -> Bookmarks
  2377. :param book_dict: a dict having the actions text as keys and the weblinks as the values
  2378. :return: None
  2379. """
  2380. if book_dict is None:
  2381. self.defaults["global_bookmarks"].update(
  2382. {
  2383. '1': ['FlatCAM', "http://flatcam.org"],
  2384. '2': ['Backup Site', ""]
  2385. }
  2386. )
  2387. else:
  2388. self.defaults["global_bookmarks"].clear()
  2389. self.defaults["global_bookmarks"].update(book_dict)
  2390. # first try to disconnect if somehow they get connected from elsewhere
  2391. for act in self.ui.menuhelp_bookmarks.actions():
  2392. try:
  2393. act.triggered.disconnect()
  2394. except TypeError:
  2395. pass
  2396. # clear all actions except the last one who is the Bookmark manager
  2397. if act is self.ui.menuhelp_bookmarks.actions()[-1]:
  2398. pass
  2399. else:
  2400. self.ui.menuhelp_bookmarks.removeAction(act)
  2401. bm_limit = int(self.defaults["global_bookmarks_limit"])
  2402. if self.defaults["global_bookmarks"]:
  2403. # order the self.defaults["global_bookmarks"] dict keys by the value as integer
  2404. # the whole convoluted things is because when serializing the self.defaults (on app close or save)
  2405. # the JSON is first making the keys as strings (therefore I have to use strings too
  2406. # or do the conversion :(
  2407. # )
  2408. # and it is ordering them (actually I want that to make the defaults easy to search within) but making
  2409. # the '10' entry jsut after '1' therefore ordering as strings
  2410. sorted_bookmarks = sorted(list(self.defaults["global_bookmarks"].items())[:bm_limit],
  2411. key=lambda x: int(x[0]))
  2412. for entry, bookmark in sorted_bookmarks:
  2413. title = bookmark[0]
  2414. weblink = bookmark[1]
  2415. act = QtWidgets.QAction(parent=self.ui.menuhelp_bookmarks)
  2416. act.setText(title)
  2417. act.setIcon(QtGui.QIcon(self.resource_location + '/link16.png'))
  2418. # from here: https://stackoverflow.com/questions/20390323/pyqt-dynamic-generate-qmenu-action-and-connect
  2419. if title == 'Backup Site' and weblink == "":
  2420. act.triggered.connect(self.on_backup_site)
  2421. else:
  2422. act.triggered.connect(lambda sig, link=weblink: webbrowser.open(link))
  2423. self.ui.menuhelp_bookmarks.insertAction(self.ui.menuhelp_bookmarks_manager, act)
  2424. self.ui.menuhelp_bookmarks_manager.triggered.connect(self.on_bookmarks_manager)
  2425. def on_bookmarks_manager(self):
  2426. """
  2427. Adds the bookmark manager in a Tab in Plot Area
  2428. :return:
  2429. """
  2430. for idx in range(self.ui.plot_tab_area.count()):
  2431. if self.ui.plot_tab_area.tabText(idx) == _("Bookmarks Manager"):
  2432. # there can be only one instance of Bookmark Manager at one time
  2433. return
  2434. # BookDialog(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui).exec_()
  2435. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui)
  2436. self.book_dialog_tab.setObjectName("bookmarks_tab")
  2437. # add the tab if it was closed
  2438. self.ui.plot_tab_area.addTab(self.book_dialog_tab, _("Bookmarks Manager"))
  2439. # delete the absolute and relative position and messages in the infobar
  2440. self.ui.position_label.setText("")
  2441. # self.ui.rel_position_label.setText("")
  2442. # Switch plot_area to preferences page
  2443. self.ui.plot_tab_area.setCurrentWidget(self.book_dialog_tab)
  2444. def on_backup_site(self):
  2445. msgbox = QtWidgets.QMessageBox()
  2446. msgbox.setText(_("This entry will resolve to another website if:\n\n"
  2447. "1. FlatCAM.org website is down\n"
  2448. "2. Someone forked FlatCAM project and wants to point\n"
  2449. "to his own website\n\n"
  2450. "If you can't get any informations about FlatCAM beta\n"
  2451. "use the YouTube channel link from the Help menu."))
  2452. msgbox.setWindowTitle(_("Alternative website"))
  2453. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/globe16.png'))
  2454. bt_yes = msgbox.addButton(_('Close'), QtWidgets.QMessageBox.YesRole)
  2455. msgbox.setDefaultButton(bt_yes)
  2456. msgbox.exec_()
  2457. # response = msgbox.clickedButton()
  2458. def on_file_savedefaults(self):
  2459. """
  2460. Callback for menu item File->Save Defaults. Saves application default options
  2461. ``self.defaults`` to current_defaults.FlatConfig.
  2462. :return: None
  2463. """
  2464. self.preferencesUiManager.save_defaults()
  2465. def final_save(self):
  2466. """
  2467. Callback for doing a preferences save to file whenever the application is about to quit.
  2468. If the project has changes, it will ask the user to save the project.
  2469. :return: None
  2470. """
  2471. if self.save_in_progress:
  2472. self.inform.emit('[WARNING_NOTCL] %s' % _("Application is saving the project. Please wait ..."))
  2473. return
  2474. if self.should_we_save and self.collection.get_list():
  2475. msgbox = QtWidgets.QMessageBox()
  2476. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  2477. "\n"
  2478. "Do you want to Save the project?"))
  2479. msgbox.setWindowTitle(_("Save changes"))
  2480. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  2481. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  2482. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2483. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2484. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2485. msgbox.setDefaultButton(bt_yes)
  2486. msgbox.exec_()
  2487. response = msgbox.clickedButton()
  2488. if response == bt_yes:
  2489. try:
  2490. self.trayIcon.hide()
  2491. except Exception:
  2492. pass
  2493. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  2494. elif response == bt_no:
  2495. try:
  2496. self.trayIcon.hide()
  2497. except Exception:
  2498. pass
  2499. self.quit_application()
  2500. elif response == bt_cancel:
  2501. return
  2502. else:
  2503. try:
  2504. self.trayIcon.hide()
  2505. except Exception:
  2506. pass
  2507. self.quit_application()
  2508. def quit_application(self):
  2509. """
  2510. Called (as a pyslot or not) when the application is quit.
  2511. :return: None
  2512. """
  2513. self.preferencesUiManager.save_defaults(silent=True)
  2514. log.debug("App.quit_application() --> App Defaults saved.")
  2515. if self.cmd_line_headless != 1:
  2516. # save app state to file
  2517. stgs = QSettings("Open Source", "FlatCAM")
  2518. stgs.setValue('saved_gui_state', self.ui.saveState())
  2519. stgs.setValue('maximized_gui', self.ui.isMaximized())
  2520. stgs.setValue(
  2521. 'language',
  2522. self.ui.general_defaults_form.general_app_group.language_cb.get_value()
  2523. )
  2524. stgs.setValue(
  2525. 'notebook_font_size',
  2526. self.ui.general_defaults_form.general_app_set_group.notebook_font_size_spinner.get_value()
  2527. )
  2528. stgs.setValue(
  2529. 'axis_font_size',
  2530. self.ui.general_defaults_form.general_app_set_group.axis_font_size_spinner.get_value()
  2531. )
  2532. stgs.setValue(
  2533. 'textbox_font_size',
  2534. self.ui.general_defaults_form.general_app_set_group.textbox_font_size_spinner.get_value()
  2535. )
  2536. stgs.setValue(
  2537. 'hud_font_size',
  2538. self.ui.general_defaults_form.general_app_set_group.hud_font_size_spinner.get_value()
  2539. )
  2540. stgs.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  2541. stgs.setValue(
  2542. 'machinist',
  2543. 1 if self.ui.general_defaults_form.general_app_set_group.machinist_cb.get_value() else 0
  2544. )
  2545. # This will write the setting to the platform specific storage.
  2546. del stgs
  2547. log.debug("App.quit_application() --> App UI state saved.")
  2548. # try to quit the Socket opened by ArgsThread class
  2549. try:
  2550. self.new_launch.stop.emit()
  2551. except Exception as err:
  2552. log.debug("App.quit_application() --> %s" % str(err))
  2553. # try to quit the QThread that run ArgsThread class
  2554. try:
  2555. self.th.quit()
  2556. except Exception as e:
  2557. log.debug("App.quit_application() --> %s" % str(e))
  2558. # terminate workers
  2559. self.workers.__del__()
  2560. # quit app by signalling for self.kill_app() method
  2561. # self.close_app_signal.emit()
  2562. QtWidgets.qApp.quit()
  2563. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2564. # we use the following command
  2565. minor_v = sys.version_info.minor
  2566. if minor_v < 8:
  2567. sys.exit(0)
  2568. else:
  2569. os._exit(0) # fix to work with Python 3.8
  2570. @staticmethod
  2571. def kill_app():
  2572. QtWidgets.qApp.quit()
  2573. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2574. # we use the following command
  2575. sys.exit(0)
  2576. def on_portable_checked(self, state):
  2577. """
  2578. Callback called when the checkbox in Preferences GUI is checked.
  2579. It will set the application as portable by creating the preferences and recent files in the
  2580. 'config' folder found in the FlatCAM installation folder.
  2581. :param state: boolean, the state of the checkbox when clicked/checked
  2582. :return:
  2583. """
  2584. line_no = 0
  2585. data = None
  2586. if sys.platform != 'win32':
  2587. # this won't work in Linux or MacOS
  2588. return
  2589. # test if the app was frozen and choose the path for the configuration file
  2590. if getattr(sys, "frozen", False) is True:
  2591. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  2592. else:
  2593. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  2594. config_file = current_data_path + '\\configuration.txt'
  2595. try:
  2596. with open(config_file, 'r') as f:
  2597. try:
  2598. data = f.readlines()
  2599. except Exception as e:
  2600. log.debug('App.__init__() -->%s' % str(e))
  2601. return
  2602. except FileNotFoundError:
  2603. pass
  2604. for line in data:
  2605. line = line.strip('\n')
  2606. param = str(line).rpartition('=')
  2607. if param[0] == 'portable':
  2608. break
  2609. line_no += 1
  2610. if state:
  2611. data[line_no] = 'portable=True\n'
  2612. # create the new defauults files
  2613. # create current_defaults.FlatConfig file if there is none
  2614. try:
  2615. f = open(current_data_path + '/current_defaults.FlatConfig')
  2616. f.close()
  2617. except IOError:
  2618. App.log.debug('Creating empty current_defaults.FlatConfig')
  2619. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  2620. json.dump({}, f)
  2621. f.close()
  2622. # create factory_defaults.FlatConfig file if there is none
  2623. try:
  2624. f = open(current_data_path + '/factory_defaults.FlatConfig')
  2625. f.close()
  2626. except IOError:
  2627. App.log.debug('Creating empty factory_defaults.FlatConfig')
  2628. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  2629. json.dump({}, f)
  2630. f.close()
  2631. try:
  2632. f = open(current_data_path + '/recent.json')
  2633. f.close()
  2634. except IOError:
  2635. App.log.debug('Creating empty recent.json')
  2636. f = open(current_data_path + '/recent.json', 'w')
  2637. json.dump([], f)
  2638. f.close()
  2639. try:
  2640. fp = open(current_data_path + '/recent_projects.json')
  2641. fp.close()
  2642. except IOError:
  2643. App.log.debug('Creating empty recent_projects.json')
  2644. fp = open(current_data_path + '/recent_projects.json', 'w')
  2645. json.dump([], fp)
  2646. fp.close()
  2647. # save the current defaults to the new defaults file
  2648. self.preferencesUiManager.save_defaults(silent=True, data_path=current_data_path)
  2649. else:
  2650. data[line_no] = 'portable=False\n'
  2651. with open(config_file, 'w') as f:
  2652. f.writelines(data)
  2653. def on_register_files(self, obj_type=None):
  2654. """
  2655. Called whenever there is a need to register file extensions with FlatCAM.
  2656. Works only in Windows and should be called only when FlatCAM is run in Windows.
  2657. :param obj_type: the type of object to be register for.
  2658. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  2659. :return: None
  2660. """
  2661. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  2662. new_reg_path = 'Software\\Classes\\'
  2663. # find if the current user is admin
  2664. try:
  2665. is_admin = os.getuid() == 0
  2666. except AttributeError:
  2667. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  2668. if is_admin is True:
  2669. root_path = winreg.HKEY_LOCAL_MACHINE
  2670. else:
  2671. root_path = winreg.HKEY_CURRENT_USER
  2672. # create the keys
  2673. def set_reg(name, root_pth, new_reg_path, value):
  2674. try:
  2675. winreg.CreateKey(root_pth, new_reg_path)
  2676. with winreg.OpenKey(root_pth, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  2677. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  2678. return True
  2679. except WindowsError:
  2680. return False
  2681. # delete key in registry
  2682. def delete_reg(root_pth, reg_path, key_to_del):
  2683. key_to_del_path = reg_path + key_to_del
  2684. try:
  2685. winreg.DeleteKey(root_pth, key_to_del_path)
  2686. return True
  2687. except WindowsError:
  2688. return False
  2689. if obj_type is None or obj_type == 'excellon':
  2690. exc_list = \
  2691. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  2692. exc_list = [x for x in exc_list if x != '']
  2693. # register all keys in the Preferences window
  2694. for ext in exc_list:
  2695. new_k = new_reg_path + '.%s' % ext
  2696. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  2697. # and unregister those that are no longer in the Preferences windows but are in the file
  2698. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  2699. if ext not in exc_list:
  2700. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  2701. # now write the updated extensions to the self.defaults
  2702. # new_ext = ''
  2703. # for ext in exc_list:
  2704. # new_ext = new_ext + ext + ', '
  2705. # self.defaults["fa_excellon"] = new_ext
  2706. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  2707. if obj_type is None or obj_type == 'gcode':
  2708. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  2709. gco_list = [x for x in gco_list if x != '']
  2710. # register all keys in the Preferences window
  2711. for ext in gco_list:
  2712. new_k = new_reg_path + '.%s' % ext
  2713. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  2714. # and unregister those that are no longer in the Preferences windows but are in the file
  2715. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  2716. if ext not in gco_list:
  2717. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  2718. # now write the updated extensions to the self.defaults
  2719. # new_ext = ''
  2720. # for ext in gco_list:
  2721. # new_ext = new_ext + ext + ', '
  2722. # self.defaults["fa_gcode"] = new_ext
  2723. self.inform.emit('[success] %s' %
  2724. _("Selected GCode file extensions registered with FlatCAM."))
  2725. if obj_type is None or obj_type == 'gerber':
  2726. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  2727. grb_list = [x for x in grb_list if x != '']
  2728. # register all keys in the Preferences window
  2729. for ext in grb_list:
  2730. new_k = new_reg_path + '.%s' % ext
  2731. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  2732. # and unregister those that are no longer in the Preferences windows but are in the file
  2733. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  2734. if ext not in grb_list:
  2735. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  2736. # now write the updated extensions to the self.defaults
  2737. # new_ext = ''
  2738. # for ext in grb_list:
  2739. # new_ext = new_ext + ext + ', '
  2740. # self.defaults["fa_gerber"] = new_ext
  2741. self.inform.emit('[success] %s' %
  2742. _("Selected Gerber file extensions registered with FlatCAM."))
  2743. def add_extension(self, ext_type):
  2744. """
  2745. Add a file extension to the list for a specific object
  2746. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  2747. :return:
  2748. """
  2749. if ext_type == 'excellon':
  2750. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  2751. if new_ext == '':
  2752. return
  2753. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  2754. if new_ext in old_val:
  2755. return
  2756. old_val.append(new_ext)
  2757. old_val.sort()
  2758. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  2759. if ext_type == 'gcode':
  2760. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  2761. if new_ext == '':
  2762. return
  2763. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  2764. if new_ext in old_val:
  2765. return
  2766. old_val.append(new_ext)
  2767. old_val.sort()
  2768. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  2769. if ext_type == 'gerber':
  2770. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  2771. if new_ext == '':
  2772. return
  2773. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  2774. if new_ext in old_val:
  2775. return
  2776. old_val.append(new_ext)
  2777. old_val.sort()
  2778. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  2779. if ext_type == 'keyword':
  2780. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  2781. if new_kw == '':
  2782. return
  2783. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  2784. if new_kw in old_val:
  2785. return
  2786. old_val.append(new_kw)
  2787. old_val.sort()
  2788. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  2789. # update the self.myKeywords so the model is updated
  2790. self.autocomplete_kw_list = \
  2791. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  2792. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  2793. self.shell._edit.set_model_data(self.myKeywords)
  2794. def del_extension(self, ext_type):
  2795. """
  2796. Remove a file extension from the list for a specific object
  2797. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  2798. :return:
  2799. """
  2800. if ext_type == 'excellon':
  2801. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  2802. if new_ext == '':
  2803. return
  2804. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  2805. if new_ext not in old_val:
  2806. return
  2807. old_val.remove(new_ext)
  2808. old_val.sort()
  2809. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  2810. if ext_type == 'gcode':
  2811. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  2812. if new_ext == '':
  2813. return
  2814. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  2815. if new_ext not in old_val:
  2816. return
  2817. old_val.remove(new_ext)
  2818. old_val.sort()
  2819. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  2820. if ext_type == 'gerber':
  2821. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  2822. if new_ext == '':
  2823. return
  2824. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  2825. if new_ext not in old_val:
  2826. return
  2827. old_val.remove(new_ext)
  2828. old_val.sort()
  2829. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  2830. if ext_type == 'keyword':
  2831. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  2832. if new_kw == '':
  2833. return
  2834. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  2835. if new_kw not in old_val:
  2836. return
  2837. old_val.remove(new_kw)
  2838. old_val.sort()
  2839. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  2840. # update the self.myKeywords so the model is updated
  2841. self.autocomplete_kw_list = \
  2842. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  2843. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  2844. self.shell._edit.set_model_data(self.myKeywords)
  2845. def restore_extensions(self, ext_type):
  2846. """
  2847. Restore all file extensions associations with FlatCAM, for a specific object
  2848. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  2849. :return:
  2850. """
  2851. if ext_type == 'excellon':
  2852. # don't add 'txt' to the associations (too many files are .txt and not Excellon) but keep it in the list
  2853. # for the ability to open Excellon files with .txt extension
  2854. new_exc_list = deepcopy(self.exc_list)
  2855. try:
  2856. new_exc_list.remove('txt')
  2857. except ValueError:
  2858. pass
  2859. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(new_exc_list))
  2860. if ext_type == 'gcode':
  2861. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(self.gcode_list))
  2862. if ext_type == 'gerber':
  2863. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(self.grb_list))
  2864. if ext_type == 'keyword':
  2865. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(self.default_keywords))
  2866. # update the self.myKeywords so the model is updated
  2867. self.autocomplete_kw_list = self.default_keywords
  2868. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  2869. self.shell._edit.set_model_data(self.myKeywords)
  2870. def delete_all_extensions(self, ext_type):
  2871. """
  2872. Delete all file extensions associations with FlatCAM, for a specific object
  2873. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  2874. :return:
  2875. """
  2876. if ext_type == 'excellon':
  2877. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value('')
  2878. if ext_type == 'gcode':
  2879. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value('')
  2880. if ext_type == 'gerber':
  2881. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value('')
  2882. if ext_type == 'keyword':
  2883. self.ui.util_defaults_form.kw_group.kw_list_text.set_value('')
  2884. # update the self.myKeywords so the model is updated
  2885. self.myKeywords = self.tcl_commands_list + self.tcl_keywords
  2886. self.shell._edit.set_model_data(self.myKeywords)
  2887. def on_edit_join(self, name=None):
  2888. """
  2889. Callback for Edit->Join. Joins the selected geometry objects into
  2890. a new one.
  2891. :return: None
  2892. """
  2893. self.defaults.report_usage("on_edit_join()")
  2894. obj_name_single = str(name) if name else "Combo_SingleGeo"
  2895. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  2896. geo_type_set = set()
  2897. objs = self.collection.get_selected()
  2898. if len(objs) < 2:
  2899. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  2900. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  2901. return 'fail'
  2902. for obj in objs:
  2903. geo_type_set.add(obj.multigeo)
  2904. # if len(geo_type_list) == 1 means that all list elements are the same
  2905. if len(geo_type_set) != 1:
  2906. self.inform.emit('[ERROR] %s' %
  2907. _("Failed join. The Geometry objects are of different types.\n"
  2908. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  2909. "convert from one to another and retry joining \n"
  2910. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  2911. "the result may not be what was expected. \n"
  2912. "Check the generated GCODE."))
  2913. return
  2914. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  2915. if True in geo_type_set:
  2916. def initialize(geo_obj, app):
  2917. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=True)
  2918. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  2919. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  2920. for v in geo_obj.tools.values():
  2921. v['data']['name'] = obj_name_multi
  2922. self.app_obj.new_object("geometry", obj_name_multi, initialize)
  2923. else:
  2924. def initialize(geo_obj, app):
  2925. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=False)
  2926. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  2927. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  2928. for v in geo_obj.tools.values():
  2929. v['data']['name'] = obj_name_single
  2930. self.app_obj.new_object("geometry", obj_name_single, initialize)
  2931. self.should_we_save = True
  2932. def on_edit_join_exc(self):
  2933. """
  2934. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  2935. a new Excellon.
  2936. :return: None
  2937. """
  2938. self.defaults.report_usage("on_edit_join_exc()")
  2939. objs = self.collection.get_selected()
  2940. for obj in objs:
  2941. if not isinstance(obj, ExcellonObject):
  2942. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Excellon joining works only on Excellon objects."))
  2943. return
  2944. if len(objs) < 2:
  2945. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  2946. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  2947. return 'fail'
  2948. def initialize(exc_obj, app):
  2949. ExcellonObject.merge(exc_list=objs, exc_final=exc_obj, decimals=self.decimals)
  2950. app.inform.emit('[success] %s.' % _("Excellon merging finished"))
  2951. self.app_obj.new_object("excellon", 'Combo_Excellon', initialize)
  2952. self.should_we_save = True
  2953. def on_edit_join_grb(self):
  2954. """
  2955. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  2956. a new Gerber object.
  2957. :return: None
  2958. """
  2959. self.defaults.report_usage("on_edit_join_grb()")
  2960. objs = self.collection.get_selected()
  2961. for obj in objs:
  2962. if not isinstance(obj, GerberObject):
  2963. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Gerber joining works only on Gerber objects."))
  2964. return
  2965. if len(objs) < 2:
  2966. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  2967. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  2968. return 'fail'
  2969. def initialize(grb_obj, app):
  2970. GerberObject.merge(grb_list=objs, grb_final=grb_obj)
  2971. app.inform.emit('[success] %s.' % _("Gerber merging finished"))
  2972. self.app_obj.new_object("gerber", 'Combo_Gerber', initialize)
  2973. self.should_we_save = True
  2974. def on_convert_singlegeo_to_multigeo(self):
  2975. """
  2976. Called for converting a Geometry object from single-geo to multi-geo.
  2977. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  2978. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  2979. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  2980. the solid-geometry of that tool.
  2981. :return: None
  2982. """
  2983. self.defaults.report_usage("on_convert_singlegeo_to_multigeo()")
  2984. obj = self.collection.get_active()
  2985. if obj is None:
  2986. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Select a Geometry Object and try again."))
  2987. return
  2988. if not isinstance(obj, GeometryObject):
  2989. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Expected a GeometryObject, got"), type(obj)))
  2990. return
  2991. obj.multigeo = True
  2992. for tooluid, dict_value in obj.tools.items():
  2993. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  2994. if not isinstance(obj.solid_geometry, list):
  2995. obj.solid_geometry = [obj.solid_geometry]
  2996. # obj.solid_geometry[:] = []
  2997. obj.plot()
  2998. self.should_we_save = True
  2999. self.inform.emit('[success] %s' % _("A Geometry object was converted to MultiGeo type."))
  3000. def on_convert_multigeo_to_singlegeo(self):
  3001. """
  3002. Called for converting a Geometry object from multi-geo to single-geo.
  3003. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3004. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3005. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3006. the solid-geometry of that tool.
  3007. :return: None
  3008. """
  3009. self.defaults.report_usage("on_convert_multigeo_to_singlegeo()")
  3010. obj = self.collection.get_active()
  3011. if obj is None:
  3012. self.inform.emit('[ERROR_NOTCL] %s' %
  3013. _("Failed. Select a Geometry Object and try again."))
  3014. return
  3015. if not isinstance(obj, GeometryObject):
  3016. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  3017. (_("Expected a GeometryObject, got"), type(obj)))
  3018. return
  3019. obj.multigeo = False
  3020. total_solid_geometry = []
  3021. for tooluid, dict_value in obj.tools.items():
  3022. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  3023. # clear the original geometry
  3024. dict_value['solid_geometry'][:] = []
  3025. obj.solid_geometry = deepcopy(total_solid_geometry)
  3026. obj.plot()
  3027. self.should_we_save = True
  3028. self.inform.emit('[success] %s' %
  3029. _("A Geometry object was converted to SingleGeo type."))
  3030. def on_defaults_dict_change(self, field):
  3031. """
  3032. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  3033. Edit -> Preferences tab window.
  3034. :param field: the key of the self.defaults dictionary that was changed.
  3035. :return: None
  3036. """
  3037. self.preferencesUiManager.defaults_write_form_field(field=field)
  3038. if field == "units":
  3039. self.set_screen_units(self.defaults['units'])
  3040. def set_screen_units(self, units):
  3041. """
  3042. Set the FlatCAM units on the status bar.
  3043. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  3044. :return: None
  3045. """
  3046. self.ui.units_label.setText("[" + units.lower() + "]")
  3047. def on_toggle_units_click(self):
  3048. try:
  3049. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  3050. except (TypeError, AttributeError):
  3051. pass
  3052. if self.defaults["units"] == 'MM':
  3053. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  3054. else:
  3055. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  3056. self.on_toggle_units(no_pref=True)
  3057. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  3058. lambda: self.on_toggle_units(no_pref=False))
  3059. def on_toggle_units(self, no_pref=False):
  3060. """
  3061. Callback for the Units radio-button change in the Preferences tab.
  3062. Changes the application's default units adn for the project too.
  3063. If changing the project's units, the change propagates to all of
  3064. the objects in the project.
  3065. :return: None
  3066. """
  3067. self.defaults.report_usage("on_toggle_units")
  3068. if self.toggle_units_ignore:
  3069. return
  3070. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3071. # If option is the same, then ignore
  3072. if new_units == self.defaults["units"].upper():
  3073. self.log.debug("on_toggle_units(): Same as previous, ignoring.")
  3074. return
  3075. # Keys in self.defaults for which to scale their values
  3076. dimensions = ['gerber_isotooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin',
  3077. "gerber_editor_newsize", "gerber_editor_lin_pitch", "gerber_editor_buff_f", "gerber_vtipdia",
  3078. "gerber_vcutz", "gerber_editor_newdim", "gerber_editor_ma_low",
  3079. "gerber_editor_ma_high",
  3080. 'excellon_cutz', 'excellon_travelz', "excellon_toolchangexy", 'excellon_offset',
  3081. 'excellon_feedrate_z', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  3082. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', 'excellon_endxy',
  3083. "excellon_feedrate_probe", "excellon_milling_dia",
  3084. "excellon_z_pdepth", "excellon_editor_newdia", "excellon_editor_lin_pitch",
  3085. "excellon_editor_slot_lin_pitch", "excellon_editor_slot_length",
  3086. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  3087. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  3088. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', 'geometry_endxy',
  3089. "geometry_extracut_length", "geometry_z_pdepth",
  3090. "geometry_feedrate_probe", "geometry_startz", "geometry_segx", "geometry_segy",
  3091. 'cncjob_tooldia',
  3092. 'tools_paintmargin', 'tools_painttooldia', "tools_paintcutz", "tools_painttipdia",
  3093. "tools_paintnewdia",
  3094. "tools_ncctools", "tools_nccmargin", "tools_ncccutz", "tools_ncctipdia",
  3095. "tools_nccnewdia", "tools_ncc_offset_value",
  3096. "tools_2sided_drilldia",
  3097. "tools_film_boundary", "tools_film_scale_stroke",
  3098. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize', "tools_cutout_z",
  3099. "tools_cutout_depthperpass",
  3100. "tools_panelize_constrainx", "tools_panelize_constrainy", "tools_panelize_spacing_columns",
  3101. "tools_panelize_spacing_rows",
  3102. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  3103. "tools_transform_offset_x", "tools_transform_offset_y", "tools_transform_mirror_point",
  3104. "tools_transform_buffer_dis",
  3105. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  3106. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  3107. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  3108. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  3109. "tools_cr_trace_size_val", "tools_cr_c2c_val", "tools_cr_c2o_val", "tools_cr_s2s_val",
  3110. "tools_cr_s2sm_val", "tools_cr_s2o_val", "tools_cr_sm2sm_val", "tools_cr_ri_val",
  3111. "tools_cr_h2h_val", "tools_cr_dh_val",
  3112. "tools_fiducials_dia", "tools_fiducials_margin", "tools_fiducials_line_thickness",
  3113. "tools_copper_thieving_clearance", "tools_copper_thieving_margin",
  3114. "tools_copper_thieving_dots_dia", "tools_copper_thieving_dots_spacing",
  3115. "tools_copper_thieving_squares_size", "tools_copper_thieving_squares_spacing",
  3116. "tools_copper_thieving_lines_size", "tools_copper_thieving_lines_spacing",
  3117. "tools_copper_thieving_rb_margin", "tools_copper_thieving_rb_thickness",
  3118. "tools_copper_thieving_mask_clearance",
  3119. "tools_cal_travelz", "tools_cal_verz", "tools_cal_toolchangez", "tools_cal_toolchange_xy",
  3120. "tools_edrills_hole_fixed_dia", "tools_edrills_circular_ring", "tools_edrills_oblong_ring",
  3121. "tools_edrills_square_ring", "tools_edrills_rectangular_ring", "tools_edrills_others_ring",
  3122. "tools_punch_hole_fixed_dia", "tools_punch_circular_ring", "tools_punch_oblong_ring",
  3123. "tools_punch_square_ring", "tools_punch_rectangular_ring", "tools_punch_others_ring",
  3124. "tools_invert_margin",
  3125. 'global_gridx', 'global_gridy', 'global_snap_max', "global_tolerance",
  3126. 'global_tpdf_bmargin', 'global_tpdf_tmargin', 'global_tpdf_rmargin', 'global_tpdf_lmargin']
  3127. def scale_defaults(sfactor):
  3128. for dim in dimensions:
  3129. if dim in [
  3130. 'gerber_editor_newdim', 'excellon_toolchangexy', 'geometry_toolchangexy', 'excellon_endxy',
  3131. 'geometry_endxy', 'tools_solderpaste_xy_toolchange', 'tools_cal_toolchange_xy',
  3132. 'tools_transform_mirror_point'
  3133. ]:
  3134. if self.defaults[dim] is None or self.defaults[dim] == '':
  3135. continue
  3136. try:
  3137. coordinates = self.defaults[dim].split(",")
  3138. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3139. coords_xy[0] *= sfactor
  3140. coords_xy[1] *= sfactor
  3141. self.defaults[dim] = "%.*f, %.*f" % (
  3142. self.decimals, coords_xy[0], self.decimals, coords_xy[1])
  3143. except Exception as e:
  3144. log.debug("App.on_toggle_units.scale_defaults() --> 'string tuples': %s" % str(e))
  3145. elif dim in [
  3146. 'geometry_cnctooldia', 'tools_ncctools', 'tools_solderpaste_tools'
  3147. ]:
  3148. if self.defaults[dim] is None or self.defaults[dim] == '':
  3149. continue
  3150. try:
  3151. self.defaults[dim] = float(self.defaults[dim])
  3152. tools_diameters = [self.defaults[dim]]
  3153. except ValueError:
  3154. try:
  3155. tools_string = self.defaults[dim].split(",")
  3156. tools_diameters = [eval(a) for a in tools_string if a != '']
  3157. except Exception as e:
  3158. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3159. continue
  3160. self.defaults[dim] = ''
  3161. td_len = len(tools_diameters)
  3162. if td_len > 1:
  3163. for t in range(td_len):
  3164. tools_diameters[t] *= sfactor
  3165. self.defaults[dim] += "%.*f," % (self.decimals, tools_diameters[t])
  3166. else:
  3167. tools_diameters[0] *= sfactor
  3168. self.defaults[dim] += "%.*f" % (self.decimals, tools_diameters[0])
  3169. elif dim in ['global_gridx', 'global_gridy']:
  3170. # format the number of decimals to the one specified in self.decimals
  3171. try:
  3172. val = float(self.defaults[dim]) * sfactor
  3173. except Exception as e:
  3174. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3175. continue
  3176. self.defaults[dim] = float('%.*f' % (self.decimals, val))
  3177. else:
  3178. # the number of decimals for the rest is kept unchanged
  3179. if self.defaults[dim]:
  3180. try:
  3181. val = float(self.defaults[dim]) * sfactor
  3182. except Exception as e:
  3183. log.debug('App.on_toggle_units().scale_defaults() --> Value: %s %s' % (str(dim), str(e)))
  3184. continue
  3185. self.defaults[dim] = val
  3186. # The scaling factor depending on choice of units.
  3187. factor = 25.4 if new_units == 'MM' else 1 / 25.4
  3188. # Changing project units. Warn user.
  3189. msgbox = QtWidgets.QMessageBox()
  3190. msgbox.setWindowTitle(_("Toggle Units"))
  3191. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/toggle_units32.png'))
  3192. msgbox.setText(_("Changing the units of the project\n"
  3193. "will scale all objects.\n\n"
  3194. "Do you want to continue?"))
  3195. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3196. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3197. msgbox.setDefaultButton(bt_ok)
  3198. msgbox.exec_()
  3199. response = msgbox.clickedButton()
  3200. if response == bt_ok:
  3201. if no_pref is False:
  3202. self.preferencesUiManager.defaults_read_form()
  3203. scale_defaults(factor)
  3204. self.preferencesUiManager.defaults_write_form(fl_units=new_units)
  3205. self.defaults["units"] = new_units
  3206. # update the defaults from form, some may assume that the conversion is enough and it's not
  3207. self.on_options_app2project()
  3208. # update the objects
  3209. for obj in self.collection.get_list():
  3210. obj.convert_units(new_units)
  3211. # make that the properties stored in the object are also updated
  3212. self.app_obj.object_changed.emit(obj)
  3213. # rebuild the object UI
  3214. obj.build_ui()
  3215. # change this only if the workspace is active
  3216. if self.defaults['global_workspace'] is True:
  3217. self.plotcanvas.draw_workspace(pagesize=self.defaults['global_workspaceT'])
  3218. # adjust the grid values on the main toolbar
  3219. val_x = float(self.defaults['global_gridx']) * factor
  3220. val_y = val_x if self.ui.grid_gap_link_cb.isChecked() else float(self.defaults['global_gridx']) * factor
  3221. current = self.collection.get_active()
  3222. if current is not None:
  3223. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  3224. if not isinstance(current, GeometryObject):
  3225. current.to_form()
  3226. # replot all objects
  3227. self.plot_all()
  3228. # set the status labels to reflect the current FlatCAM units
  3229. self.set_screen_units(new_units)
  3230. # signal to the app that we changed the object properties and it should save the project
  3231. self.should_we_save = True
  3232. self.inform.emit('[success] %s: %s' % (_("Converted units to"), new_units))
  3233. else:
  3234. # Undo toggling
  3235. self.toggle_units_ignore = True
  3236. if self.defaults['units'].upper() == 'MM':
  3237. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  3238. else:
  3239. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  3240. self.toggle_units_ignore = False
  3241. # store the grid values so they are not changed in the next step
  3242. val_x = float(self.defaults['global_gridx'])
  3243. val_y = float(self.defaults['global_gridy'])
  3244. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  3245. self.preferencesUiManager.defaults_read_form()
  3246. # the self.preferencesUiManager.defaults_read_form() will update all defaults values
  3247. # in self.defaults from the GUI elements but
  3248. # I don't want it for the grid values, so I update them here
  3249. self.defaults['global_gridx'] = val_x
  3250. self.defaults['global_gridy'] = val_y
  3251. self.ui.grid_gap_x_entry.set_value(val_x, decimals=self.decimals)
  3252. self.ui.grid_gap_y_entry.set_value(val_y, decimals=self.decimals)
  3253. def on_toggle_axis(self):
  3254. self.defaults.report_usage("on_toggle_axis()")
  3255. if self.toggle_axis is False:
  3256. if self.is_legacy is False:
  3257. self.plotcanvas.v_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=True,
  3258. parent=self.plotcanvas.view.scene)
  3259. self.plotcanvas.h_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=False,
  3260. parent=self.plotcanvas.view.scene)
  3261. else:
  3262. if self.plotcanvas.h_line not in self.plotcanvas.axes.lines and \
  3263. self.plotcanvas.v_line not in self.plotcanvas.axes.lines:
  3264. self.plotcanvas.h_line = self.plotcanvas.axes.axhline(color=(0.70, 0.3, 0.3), linewidth=2)
  3265. self.plotcanvas.v_line = self.plotcanvas.axes.axvline(color=(0.70, 0.3, 0.3), linewidth=2)
  3266. self.plotcanvas.canvas.draw()
  3267. self.inform.emit(_("Axis enabled."))
  3268. self.toggle_axis = True
  3269. else:
  3270. if self.is_legacy is False:
  3271. self.plotcanvas.v_line.parent = None
  3272. self.plotcanvas.h_line.parent = None
  3273. else:
  3274. if self.plotcanvas.h_line in self.plotcanvas.axes.lines and \
  3275. self.plotcanvas.v_line in self.plotcanvas.axes.lines:
  3276. self.plotcanvas.axes.lines.remove(self.plotcanvas.h_line)
  3277. self.plotcanvas.axes.lines.remove(self.plotcanvas.v_line)
  3278. self.plotcanvas.canvas.draw()
  3279. self.inform.emit(_("Axis disabled."))
  3280. self.toggle_axis = False
  3281. def on_toggle_hud(self):
  3282. new_state = False if self.plotcanvas.hud_enabled else True
  3283. self.plotcanvas.on_toggle_hud(state=new_state)
  3284. if new_state is False:
  3285. self.inform.emit(_("HUD disabled."))
  3286. else:
  3287. self.inform.emit(_("HUD enabled."))
  3288. def on_toggle_grid_lines(self):
  3289. self.defaults.report_usage("on_toggle_grd_lines()")
  3290. tt_settings = QtCore.QSettings("Open Source", "FlatCAM")
  3291. if tt_settings.contains("theme"):
  3292. theme = tt_settings.value('theme', type=str)
  3293. else:
  3294. theme = 'white'
  3295. if self.toggle_grid_lines is False:
  3296. if self.is_legacy is False:
  3297. if theme == 'white':
  3298. self.plotcanvas.grid._grid_color_fn['color'] = Color('dimgray').rgba
  3299. else:
  3300. self.plotcanvas.grid._grid_color_fn['color'] = Color('#dededeff').rgba
  3301. else:
  3302. self.plotcanvas.axes.grid(True)
  3303. try:
  3304. self.plotcanvas.canvas.draw()
  3305. except IndexError:
  3306. pass
  3307. pass
  3308. self.inform.emit(_("Grid enabled."))
  3309. self.toggle_grid_lines = True
  3310. else:
  3311. if self.is_legacy is False:
  3312. if theme == 'white':
  3313. self.plotcanvas.grid._grid_color_fn['color'] = Color('#ffffffff').rgba
  3314. else:
  3315. self.plotcanvas.grid._grid_color_fn['color'] = Color('#000000FF').rgba
  3316. else:
  3317. self.plotcanvas.axes.grid(False)
  3318. try:
  3319. self.plotcanvas.canvas.draw()
  3320. except IndexError:
  3321. pass
  3322. self.toggle_grid_lines = False
  3323. self.inform.emit(_("Grid disabled."))
  3324. if self.is_legacy is False:
  3325. # HACK: enabling/disabling the cursor seams to somehow update the shapes on screen
  3326. # - perhaps is a bug in VisPy implementation
  3327. if self.grid_status():
  3328. self.app_cursor.enabled = False
  3329. self.app_cursor.enabled = True
  3330. else:
  3331. self.app_cursor.enabled = True
  3332. self.app_cursor.enabled = False
  3333. def on_tab_rmb_click(self, checked):
  3334. self.ui.notebook.set_detachable(val=checked)
  3335. self.defaults["global_tabs_detachable"] = checked
  3336. self.ui.plot_tab_area.set_detachable(val=checked)
  3337. self.defaults["global_tabs_detachable"] = checked
  3338. def on_tab_setup_context_menu(self):
  3339. initial_checked = self.defaults["global_tabs_detachable"]
  3340. action_name = str(_("Detachable Tabs"))
  3341. action = QtWidgets.QAction(self)
  3342. action.setCheckable(True)
  3343. action.setText(action_name)
  3344. action.setChecked(initial_checked)
  3345. self.ui.notebook.tabBar.addAction(action)
  3346. self.ui.plot_tab_area.tabBar.addAction(action)
  3347. try:
  3348. action.triggered.disconnect()
  3349. except TypeError:
  3350. pass
  3351. action.triggered.connect(self.on_tab_rmb_click)
  3352. def on_deselect_all(self):
  3353. self.collection.set_all_inactive()
  3354. self.delete_selection_shape()
  3355. def on_workspace_modified(self):
  3356. # self.save_defaults(silent=True)
  3357. self.plotcanvas.delete_workspace()
  3358. self.preferencesUiManager.defaults_read_form()
  3359. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  3360. def on_workspace(self):
  3361. if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value():
  3362. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  3363. self.inform.emit(_("Workspace enabled."))
  3364. else:
  3365. self.plotcanvas.delete_workspace()
  3366. self.inform.emit(_("Workspace disabled."))
  3367. self.preferencesUiManager.defaults_read_form()
  3368. # self.save_defaults(silent=True)
  3369. def on_workspace_toggle(self):
  3370. state = False if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value() else True
  3371. try:
  3372. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.disconnect(self.on_workspace)
  3373. except TypeError:
  3374. pass
  3375. self.ui.general_defaults_form.general_app_set_group.workspace_cb.set_value(state)
  3376. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  3377. self.on_workspace()
  3378. def on_cursor_type(self, val):
  3379. """
  3380. :param val: type of mouse cursor, set in Preferences ('small' or 'big')
  3381. :return: None
  3382. """
  3383. self.app_cursor.enabled = False
  3384. if val == 'small':
  3385. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(False)
  3386. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(False)
  3387. self.app_cursor = self.plotcanvas.new_cursor()
  3388. else:
  3389. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(True)
  3390. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(True)
  3391. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  3392. if self.ui.grid_snap_btn.isChecked():
  3393. self.app_cursor.enabled = True
  3394. else:
  3395. self.app_cursor.enabled = False
  3396. def on_tool_add_keypress(self):
  3397. # ## Current application units in Upper Case
  3398. self.units = self.defaults['units'].upper()
  3399. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3400. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  3401. if notebook_widget_name == 'selected_tab':
  3402. if self.collection.get_active().kind == 'geometry':
  3403. # Tool add works for Geometry only if Advanced is True in Preferences
  3404. if self.defaults["global_app_level"] == 'a':
  3405. tool_add_popup = FCInputDialog(title="New Tool ...",
  3406. text='Enter a Tool Diameter:',
  3407. min=0.0000, max=99.9999, decimals=4)
  3408. tool_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/letter_t_32.png'))
  3409. val, ok = tool_add_popup.get_value()
  3410. if ok:
  3411. if float(val) == 0:
  3412. self.inform.emit('[WARNING_NOTCL] %s' %
  3413. _("Please enter a tool diameter with non-zero value, in Float format."))
  3414. return
  3415. self.collection.get_active().on_tool_add(dia=float(val))
  3416. else:
  3417. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding Tool cancelled"))
  3418. else:
  3419. msgbox = QtWidgets.QMessageBox()
  3420. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  3421. "Go to Preferences -> General - Show Advanced Options."))
  3422. msgbox.setWindowTitle("Tool adding ...")
  3423. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/warning.png'))
  3424. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3425. msgbox.setDefaultButton(bt_ok)
  3426. msgbox.exec_()
  3427. # work only if the notebook tab on focus is the Tools_Tab
  3428. if notebook_widget_name == 'tool_tab':
  3429. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3430. # and only if the tool is NCC Tool
  3431. if tool_widget == self.ncclear_tool.toolName:
  3432. self.ncclear_tool.on_add_tool_by_key()
  3433. # and only if the tool is Paint Area Tool
  3434. elif tool_widget == self.paint_tool.toolName:
  3435. self.paint_tool.on_add_tool_by_key()
  3436. # and only if the tool is Solder Paste Dispensing Tool
  3437. elif tool_widget == self.paste_tool.toolName:
  3438. self.paste_tool.on_add_tool_by_key()
  3439. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  3440. # See description below.
  3441. def on_delete_keypress(self):
  3442. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3443. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  3444. if notebook_widget_name == 'selected_tab':
  3445. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.GeometryObject'>":
  3446. self.collection.get_active().on_tool_delete()
  3447. # work only if the notebook tab on focus is the Tools_Tab
  3448. elif notebook_widget_name == 'tool_tab':
  3449. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3450. # and only if the tool is NCC Tool
  3451. if tool_widget == self.ncclear_tool.toolName:
  3452. self.ncclear_tool.on_tool_delete()
  3453. # and only if the tool is Paint Tool
  3454. elif tool_widget == self.paint_tool.toolName:
  3455. self.paint_tool.on_tool_delete()
  3456. # and only if the tool is Solder Paste Dispensing Tool
  3457. elif tool_widget == self.paste_tool.toolName:
  3458. self.paste_tool.on_tool_delete()
  3459. else:
  3460. self.on_delete()
  3461. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  3462. # some screens you have to be careful where you hover with your mouse.
  3463. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  3464. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  3465. # Complicated, I know :)
  3466. def on_delete(self, force_deletion=False):
  3467. """
  3468. Delete the currently selected FlatCAMObjs.
  3469. :param force_deletion: used by Tcl command
  3470. :return: None
  3471. """
  3472. self.defaults.report_usage("on_delete()")
  3473. response = None
  3474. bt_ok = None
  3475. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  3476. # a geometry object before we update it.
  3477. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  3478. and self.grb_editor.editor_active is False:
  3479. if self.defaults["global_delete_confirmation"] is True and force_deletion is False:
  3480. msgbox = QtWidgets.QMessageBox()
  3481. msgbox.setWindowTitle(_("Delete objects"))
  3482. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/deleteshape32.png'))
  3483. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  3484. msgbox.setText(_("Are you sure you want to permanently delete\n"
  3485. "the selected objects?"))
  3486. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3487. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3488. msgbox.setDefaultButton(bt_ok)
  3489. msgbox.exec_()
  3490. response = msgbox.clickedButton()
  3491. if self.defaults["global_delete_confirmation"] is False or force_deletion is True:
  3492. response = bt_ok
  3493. if response == bt_ok:
  3494. if self.collection.get_active():
  3495. self.log.debug("App.on_delete()")
  3496. for obj_active in self.collection.get_selected():
  3497. # if the deleted object is GerberObject then make sure to delete the possible mark shapes
  3498. if obj_active.kind == 'gerber':
  3499. for el in obj_active.mark_shapes:
  3500. obj_active.mark_shapes[el].clear(update=True)
  3501. obj_active.mark_shapes[el].enabled = False
  3502. # obj_active.mark_shapes[el] = None
  3503. del el
  3504. elif isinstance(obj_active, CNCJobObject):
  3505. try:
  3506. obj_active.text_col.enabled = False
  3507. del obj_active.text_col
  3508. obj_active.annotation.clear(update=True)
  3509. del obj_active.annotation
  3510. except AttributeError as e:
  3511. log.debug(
  3512. "App.on_delete() --> delete annotations on a FlatCAMCNCJob object. %s" % str(e)
  3513. )
  3514. while self.collection.get_selected():
  3515. self.delete_first_selected()
  3516. self.inform.emit('%s...' % _("Object(s) deleted"))
  3517. # make sure that the selection shape is deleted, too
  3518. self.delete_selection_shape()
  3519. # if there are no longer objects delete also the exclusion areas shapes
  3520. if not self.collection.get_list():
  3521. self.exc_areas.clear_shapes()
  3522. else:
  3523. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  3524. else:
  3525. self.inform.emit(_("Save the work in Editor and try again ..."))
  3526. def delete_first_selected(self):
  3527. # Keep this for later
  3528. try:
  3529. sel_obj = self.collection.get_active()
  3530. name = sel_obj.options["name"]
  3531. isPlotted = sel_obj.options["plot"]
  3532. except AttributeError:
  3533. self.log.debug("Nothing selected for deletion")
  3534. return
  3535. if self.is_legacy is True:
  3536. # Remove plot only if the object was plotted otherwise delaxes will fail
  3537. if isPlotted:
  3538. try:
  3539. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  3540. self.plotcanvas.figure.delaxes(self.collection.get_active().shapes.axes)
  3541. except Exception as e:
  3542. log.debug("App.delete_first_selected() --> %s" % str(e))
  3543. self.plotcanvas.auto_adjust_axes()
  3544. # Remove from dictionary
  3545. self.collection.delete_active()
  3546. # Clear form
  3547. self.setup_component_editor()
  3548. self.inform.emit('%s: %s' % (_("Object deleted"), name))
  3549. def on_set_origin(self):
  3550. """
  3551. Set the origin to the left mouse click position
  3552. :return: None
  3553. """
  3554. # display the message for the user
  3555. # and ask him to click on the desired position
  3556. self.defaults.report_usage("on_set_origin()")
  3557. def origin_replot():
  3558. def worker_task():
  3559. with self.proc_container.new('%s...' % _("Plotting")):
  3560. for obj in self.collection.get_list():
  3561. obj.plot()
  3562. self.plotcanvas.fit_view()
  3563. if self.is_legacy:
  3564. self.plotcanvas.graph_event_disconnect(self.mp_zc)
  3565. else:
  3566. self.plotcanvas.graph_event_disconnect('mouse_press', self.on_set_zero_click)
  3567. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3568. self.inform.emit(_('Click to set the origin ...'))
  3569. self.mp_zc = self.plotcanvas.graph_event_connect('mouse_press', self.on_set_zero_click)
  3570. # first disconnect it as it may have been used by something else
  3571. try:
  3572. self.replot_signal.disconnect()
  3573. except TypeError:
  3574. pass
  3575. self.replot_signal[list].connect(origin_replot)
  3576. def on_set_zero_click(self, event, location=None, noplot=False, use_thread=True):
  3577. """
  3578. :param event:
  3579. :param location:
  3580. :param noplot:
  3581. :param use_thread:
  3582. :return:
  3583. """
  3584. noplot_sig = noplot
  3585. def worker_task():
  3586. with self.proc_container.new(_("Setting Origin...")):
  3587. obj_list = self.collection.get_list()
  3588. for obj in obj_list:
  3589. obj.offset((x, y))
  3590. self.app_obj.object_changed.emit(obj)
  3591. # Update the object bounding box options
  3592. a, b, c, d = obj.bounds()
  3593. obj.options['xmin'] = a
  3594. obj.options['ymin'] = b
  3595. obj.options['xmax'] = c
  3596. obj.options['ymax'] = d
  3597. self.inform.emit('[success] %s...' % _('Origin set'))
  3598. for obj in obj_list:
  3599. out_name = obj.options["name"]
  3600. if obj.kind == 'gerber':
  3601. obj.source_file = self.export_gerber(
  3602. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3603. elif obj.kind == 'excellon':
  3604. obj.source_file = self.export_excellon(
  3605. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3606. if noplot_sig is False:
  3607. self.replot_signal.emit([])
  3608. if location is not None:
  3609. if len(location) != 2:
  3610. self.inform.emit('[ERROR_NOTCL] %s...' % _("Origin coordinates specified but incomplete."))
  3611. return 'fail'
  3612. x, y = location
  3613. if use_thread is True:
  3614. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3615. else:
  3616. worker_task()
  3617. self.should_we_save = True
  3618. return
  3619. if event is not None and event.button == 1:
  3620. if self.is_legacy is False:
  3621. event_pos = event.pos
  3622. else:
  3623. event_pos = (event.xdata, event.ydata)
  3624. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  3625. if self.grid_status():
  3626. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  3627. else:
  3628. pos = pos_canvas
  3629. x = 0 - pos[0]
  3630. y = 0 - pos[1]
  3631. if use_thread is True:
  3632. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3633. else:
  3634. worker_task()
  3635. self.should_we_save = True
  3636. def on_move2origin(self, use_thread=True):
  3637. """
  3638. Move selected objects to origin.
  3639. :param use_thread: Control if to use threaded operation. Boolean.
  3640. :return:
  3641. """
  3642. def worker_task():
  3643. with self.proc_container.new(_("Moving to Origin...")):
  3644. obj_list = self.collection.get_selected()
  3645. if not obj_list:
  3646. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  3647. return
  3648. xminlist = []
  3649. yminlist = []
  3650. # first get a bounding box to fit all
  3651. for obj in obj_list:
  3652. xmin, ymin, xmax, ymax = obj.bounds()
  3653. xminlist.append(xmin)
  3654. yminlist.append(ymin)
  3655. # get the minimum x,y for all objects selected
  3656. x = min(xminlist)
  3657. y = min(yminlist)
  3658. for obj in obj_list:
  3659. obj.offset((-x, -y))
  3660. self.app_obj.object_changed.emit(obj)
  3661. # Update the object bounding box options
  3662. a, b, c, d = obj.bounds()
  3663. obj.options['xmin'] = a
  3664. obj.options['ymin'] = b
  3665. obj.options['xmax'] = c
  3666. obj.options['ymax'] = d
  3667. for obj in obj_list:
  3668. obj.plot()
  3669. for obj in obj_list:
  3670. out_name = obj.options["name"]
  3671. if obj.kind == 'gerber':
  3672. obj.source_file = self.export_gerber(
  3673. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3674. elif obj.kind == 'excellon':
  3675. obj.source_file = self.export_excellon(
  3676. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3677. self.inform.emit('[success] %s...' % _('Origin set'))
  3678. if use_thread is True:
  3679. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3680. else:
  3681. worker_task()
  3682. self.should_we_save = True
  3683. def on_jump_to(self, custom_location=None, fit_center=True):
  3684. """
  3685. Jump to a location by setting the mouse cursor location.
  3686. :param custom_location: Jump to a specified point. (x, y) tuple.
  3687. :param fit_center: If to fit view. Boolean.
  3688. :return:
  3689. """
  3690. self.defaults.report_usage("on_jump_to()")
  3691. if not custom_location:
  3692. dia_box_location = None
  3693. try:
  3694. dia_box_location = eval(self.clipboard.text())
  3695. except Exception:
  3696. pass
  3697. if type(dia_box_location) == tuple:
  3698. dia_box_location = str(dia_box_location)
  3699. else:
  3700. dia_box_location = None
  3701. # dia_box = Dialog_box(title=_("Jump to ..."),
  3702. # label=_("Enter the coordinates in format X,Y:"),
  3703. # icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  3704. # initial_text=dia_box_location)
  3705. dia_box = DialogBoxRadio(title=_("Jump to ..."),
  3706. label=_("Enter the coordinates in format X,Y:"),
  3707. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  3708. initial_text=dia_box_location,
  3709. reference=self.defaults['global_jump_ref'])
  3710. if dia_box.ok is True:
  3711. try:
  3712. location = eval(dia_box.location)
  3713. if not isinstance(location, tuple):
  3714. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  3715. return
  3716. if dia_box.reference == 'rel':
  3717. rel_x = self.mouse[0] + location[0]
  3718. rel_y = self.mouse[1] + location[1]
  3719. location = (rel_x, rel_y)
  3720. self.defaults['global_jump_ref'] = dia_box.reference
  3721. except Exception:
  3722. return
  3723. else:
  3724. return
  3725. else:
  3726. location = custom_location
  3727. self.jump_signal.emit(location)
  3728. if fit_center:
  3729. self.plotcanvas.fit_center(loc=location)
  3730. cursor = QtGui.QCursor()
  3731. if self.is_legacy is False:
  3732. # I don't know where those differences come from but they are constant for the current
  3733. # execution of the application and they are multiples of a value around 0.0263mm.
  3734. # In a random way sometimes they are more sometimes they are less
  3735. # if units == 'MM':
  3736. # cal_factor = 0.0263
  3737. # else:
  3738. # cal_factor = 0.0263 / 25.4
  3739. cal_location = (location[0], location[1])
  3740. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3741. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  3742. j_pos = (
  3743. int(canvas_origin.x() + round(jump_loc[0])),
  3744. int(canvas_origin.y() + round(jump_loc[1]))
  3745. )
  3746. cursor.setPos(j_pos[0], j_pos[1])
  3747. else:
  3748. # find the canvas origin which is in the top left corner
  3749. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3750. # determine the coordinates for the lowest left point of the canvas
  3751. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  3752. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  3753. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  3754. # canvas) and the point (width, height) is in the top-right location
  3755. loc = self.plotcanvas.axes.transData.transform_point(location)
  3756. j_pos = (
  3757. int(x0 + loc[0]),
  3758. int(y0 - loc[1])
  3759. )
  3760. cursor.setPos(j_pos[0], j_pos[1])
  3761. self.plotcanvas.mouse = [location[0], location[1]]
  3762. if self.defaults["global_cursor_color_enabled"] is True:
  3763. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  3764. else:
  3765. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  3766. if self.grid_status():
  3767. # Update cursor
  3768. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  3769. symbol='++', edge_color=self.cursor_color_3D,
  3770. edge_width=self.defaults["global_cursor_width"],
  3771. size=self.defaults["global_cursor_size"])
  3772. # Set the relative position label
  3773. dx = location[0] - float(self.rel_point1[0])
  3774. dy = location[1] - float(self.rel_point1[1])
  3775. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  3776. "<b>Y</b>: %.4f&nbsp;" % (location[0], location[1]))
  3777. # # Set the position label
  3778. #
  3779. # self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  3780. # "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  3781. units = self.defaults["units"].lower()
  3782. self.plotcanvas.text_hud.text = \
  3783. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  3784. dx, units, dy, units, location[0], units, location[1], units)
  3785. self.inform.emit('[success] %s' % _("Done."))
  3786. return location
  3787. def on_locate(self, obj, fit_center=True):
  3788. """
  3789. Jump to one of the corners (or center) of an object by setting the mouse cursor location
  3790. :param obj: The object on which to locate certain points
  3791. :param fit_center: If to fit view. Boolean.
  3792. :return: A point location. (x, y) tuple.
  3793. """
  3794. self.defaults.report_usage("on_locate()")
  3795. if obj is None:
  3796. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  3797. return 'fail'
  3798. class DialogBoxChoice(QtWidgets.QDialog):
  3799. def __init__(self, title=None, icon=None, choice='bl'):
  3800. """
  3801. :param title: string with the window title
  3802. """
  3803. super(DialogBoxChoice, self).__init__()
  3804. self.ok = False
  3805. self.setWindowIcon(icon)
  3806. self.setWindowTitle(str(title))
  3807. self.form = QtWidgets.QFormLayout(self)
  3808. self.ref_radio = RadioSet([
  3809. {"label": _("Bottom-Left"), "value": "bl"},
  3810. {"label": _("Top-Left"), "value": "tl"},
  3811. {"label": _("Bottom-Right"), "value": "br"},
  3812. {"label": _("Top-Right"), "value": "tr"},
  3813. {"label": _("Center"), "value": "c"}
  3814. ], orientation='vertical', stretch=False)
  3815. self.ref_radio.set_value(choice)
  3816. self.form.addRow(self.ref_radio)
  3817. self.button_box = QtWidgets.QDialogButtonBox(
  3818. QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel,
  3819. Qt.Horizontal, parent=self)
  3820. self.form.addRow(self.button_box)
  3821. self.button_box.accepted.connect(self.accept)
  3822. self.button_box.rejected.connect(self.reject)
  3823. if self.exec_() == QtWidgets.QDialog.Accepted:
  3824. self.ok = True
  3825. self.location_point = self.ref_radio.get_value()
  3826. else:
  3827. self.ok = False
  3828. self.location_point = None
  3829. dia_box = DialogBoxChoice(title=_("Locate ..."),
  3830. icon=QtGui.QIcon(self.resource_location + '/locate16.png'),
  3831. choice=self.defaults['global_locate_pt'])
  3832. if dia_box.ok is True:
  3833. try:
  3834. location_point = dia_box.location_point
  3835. self.defaults['global_locate_pt'] = dia_box.location_point
  3836. except Exception:
  3837. return
  3838. else:
  3839. return
  3840. loc_b = obj.bounds()
  3841. if location_point == 'bl':
  3842. location = (loc_b[0], loc_b[1])
  3843. elif location_point == 'tl':
  3844. location = (loc_b[0], loc_b[3])
  3845. elif location_point == 'br':
  3846. location = (loc_b[2], loc_b[1])
  3847. elif location_point == 'tr':
  3848. location = (loc_b[2], loc_b[3])
  3849. else:
  3850. # center
  3851. cx = loc_b[0] + ((loc_b[2] - loc_b[0]) / 2)
  3852. cy = loc_b[1] + ((loc_b[3] - loc_b[1]) / 2)
  3853. location = (cx, cy)
  3854. self.locate_signal.emit(location, location_point)
  3855. if fit_center:
  3856. self.plotcanvas.fit_center(loc=location)
  3857. cursor = QtGui.QCursor()
  3858. if self.is_legacy is False:
  3859. # I don't know where those differences come from but they are constant for the current
  3860. # execution of the application and they are multiples of a value around 0.0263mm.
  3861. # In a random way sometimes they are more sometimes they are less
  3862. # if units == 'MM':
  3863. # cal_factor = 0.0263
  3864. # else:
  3865. # cal_factor = 0.0263 / 25.4
  3866. cal_location = (location[0], location[1])
  3867. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3868. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  3869. j_pos = (
  3870. int(canvas_origin.x() + round(jump_loc[0])),
  3871. int(canvas_origin.y() + round(jump_loc[1]))
  3872. )
  3873. cursor.setPos(j_pos[0], j_pos[1])
  3874. else:
  3875. # find the canvas origin which is in the top left corner
  3876. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3877. # determine the coordinates for the lowest left point of the canvas
  3878. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  3879. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  3880. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  3881. # canvas) and the point (width, height) is in the top-right location
  3882. loc = self.plotcanvas.axes.transData.transform_point(location)
  3883. j_pos = (
  3884. int(x0 + loc[0]),
  3885. int(y0 - loc[1])
  3886. )
  3887. cursor.setPos(j_pos[0], j_pos[1])
  3888. self.plotcanvas.mouse = [location[0], location[1]]
  3889. if self.defaults["global_cursor_color_enabled"] is True:
  3890. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  3891. else:
  3892. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  3893. if self.grid_status():
  3894. # Update cursor
  3895. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  3896. symbol='++', edge_color=self.cursor_color_3D,
  3897. edge_width=self.defaults["global_cursor_width"],
  3898. size=self.defaults["global_cursor_size"])
  3899. # Set the relative position label
  3900. self.dx = location[0] - float(self.rel_point1[0])
  3901. self.dy = location[1] - float(self.rel_point1[1])
  3902. # Set the position label
  3903. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  3904. "<b>Y</b>: %.4f&nbsp;" % (location[0], location[1]))
  3905. # self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  3906. # "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  3907. units = self.defaults["units"].lower()
  3908. self.plotcanvas.text_hud.text = \
  3909. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  3910. self.dx, units, self.dy, units, location[0], units, location[1], units)
  3911. self.inform.emit('[success] %s' % _("Done."))
  3912. return location
  3913. def on_copy_command(self):
  3914. """
  3915. Will copy a selection of objects, creating new objects.
  3916. :return:
  3917. """
  3918. self.defaults.report_usage("on_copy_command()")
  3919. def initialize(obj_init, app):
  3920. """
  3921. :param obj_init: the new object
  3922. :type obj_init: class
  3923. :param app: An instance of the App class
  3924. :type app: App
  3925. :return: None
  3926. :rtype:
  3927. """
  3928. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  3929. try:
  3930. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  3931. except AttributeError:
  3932. pass
  3933. try:
  3934. obj_init.apertures = deepcopy(obj.apertures)
  3935. except AttributeError:
  3936. pass
  3937. try:
  3938. if obj.tools:
  3939. obj_init.tools = deepcopy(obj.tools)
  3940. except Exception as err:
  3941. log.debug("App.on_copy_command() --> %s" % str(err))
  3942. try:
  3943. obj_init.source_file = deepcopy(obj.source_file)
  3944. except (AttributeError, TypeError):
  3945. pass
  3946. def initialize_excellon(obj_init, app):
  3947. obj_init.source_file = deepcopy(obj.source_file)
  3948. obj_init.tools = deepcopy(obj.tools)
  3949. # drills are offset, so they need to be deep copied
  3950. obj_init.drills = deepcopy(obj.drills)
  3951. # slots are offset, so they need to be deep copied
  3952. obj_init.slots = deepcopy(obj.slots)
  3953. obj_init.create_geometry()
  3954. def initialize_script(obj_init, app_obj):
  3955. obj_init.source_file = deepcopy(obj.source_file)
  3956. def initialize_document(obj_init, app_obj):
  3957. obj_init.source_file = deepcopy(obj.source_file)
  3958. for obj in self.collection.get_selected():
  3959. obj_name = obj.options["name"]
  3960. try:
  3961. if isinstance(obj, ExcellonObject):
  3962. self.app_obj.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  3963. elif isinstance(obj, GerberObject):
  3964. self.app_obj.new_object("gerber", str(obj_name) + "_copy", initialize)
  3965. elif isinstance(obj, GeometryObject):
  3966. self.app_obj.new_object("geometry", str(obj_name) + "_copy", initialize)
  3967. elif isinstance(obj, ScriptObject):
  3968. self.app_obj.new_object("script", str(obj_name) + "_copy", initialize_script)
  3969. elif isinstance(obj, DocumentObject):
  3970. self.app_obj.new_object("document", str(obj_name) + "_copy", initialize_document)
  3971. except Exception as e:
  3972. return "Operation failed: %s" % str(e)
  3973. def on_copy_object2(self, custom_name):
  3974. def initialize_geometry(obj_init, app):
  3975. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  3976. try:
  3977. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  3978. except AttributeError:
  3979. pass
  3980. try:
  3981. obj_init.apertures = deepcopy(obj.apertures)
  3982. except AttributeError:
  3983. pass
  3984. try:
  3985. if obj.tools:
  3986. obj_init.tools = deepcopy(obj.tools)
  3987. except Exception as ee:
  3988. log.debug("on_copy_object2() --> %s" % str(ee))
  3989. def initialize_gerber(obj_init, app):
  3990. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  3991. obj_init.apertures = deepcopy(obj.apertures)
  3992. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  3993. def initialize_excellon(obj_init, app):
  3994. obj_init.tools = deepcopy(obj.tools)
  3995. # drills are offset, so they need to be deep copied
  3996. obj_init.drills = deepcopy(obj.drills)
  3997. # slots are offset, so they need to be deep copied
  3998. obj_init.slots = deepcopy(obj.slots)
  3999. obj_init.create_geometry()
  4000. for obj in self.collection.get_selected():
  4001. obj_name = obj.options["name"]
  4002. try:
  4003. if isinstance(obj, ExcellonObject):
  4004. self.app_obj.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  4005. elif isinstance(obj, GerberObject):
  4006. self.app_obj.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  4007. elif isinstance(obj, GeometryObject):
  4008. self.app_obj.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  4009. except Exception as er:
  4010. return "Operation failed: %s" % str(er)
  4011. def on_rename_object(self, text):
  4012. """
  4013. Will rename an object.
  4014. :param text: New name for the object.
  4015. :return:
  4016. """
  4017. self.defaults.report_usage("on_rename_object()")
  4018. named_obj = self.collection.get_active()
  4019. for obj in named_obj:
  4020. if obj is list:
  4021. self.on_rename_object(text)
  4022. else:
  4023. try:
  4024. obj.options['name'] = text
  4025. except Exception as e:
  4026. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  4027. def convert_any2geo(self):
  4028. """
  4029. Will convert any object out of Gerber, Excellon, Geometry to Geometry object.
  4030. :return:
  4031. """
  4032. self.defaults.report_usage("convert_any2geo()")
  4033. def initialize(obj_init, app):
  4034. obj_init.solid_geometry = obj.solid_geometry
  4035. try:
  4036. obj_init.follow_geometry = obj.follow_geometry
  4037. except AttributeError:
  4038. pass
  4039. try:
  4040. obj_init.apertures = obj.apertures
  4041. except AttributeError:
  4042. pass
  4043. try:
  4044. if obj.tools:
  4045. obj_init.tools = obj.tools
  4046. except AttributeError:
  4047. pass
  4048. def initialize_excellon(obj_init, app):
  4049. # objs = self.collection.get_selected()
  4050. # GeometryObject.merge(objs, obj)
  4051. solid_geo = []
  4052. for tool in obj.tools:
  4053. for geo in obj.tools[tool]['solid_geometry']:
  4054. solid_geo.append(geo)
  4055. obj_init.solid_geometry = deepcopy(solid_geo)
  4056. if not self.collection.get_selected():
  4057. log.warning("App.convert_any2geo --> No object selected")
  4058. self.inform.emit('[WARNING_NOTCL] %s' %
  4059. _("No object is selected. Select an object and try again."))
  4060. return
  4061. for obj in self.collection.get_selected():
  4062. obj_name = obj.options["name"]
  4063. try:
  4064. if isinstance(obj, ExcellonObject):
  4065. self.app_obj.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  4066. else:
  4067. self.app_obj.new_object("geometry", str(obj_name) + "_conv", initialize)
  4068. except Exception as e:
  4069. return "Operation failed: %s" % str(e)
  4070. def convert_any2gerber(self):
  4071. """
  4072. Will convert any object out of Gerber, Excellon, Geometry to Gerber object.
  4073. :return:
  4074. """
  4075. self.defaults.report_usage("convert_any2gerber()")
  4076. def initialize_geometry(obj_init, app):
  4077. apertures = {}
  4078. apid = 0
  4079. apertures[str(apid)] = {}
  4080. apertures[str(apid)]['geometry'] = []
  4081. for obj_orig in obj.solid_geometry:
  4082. new_elem = {}
  4083. new_elem['solid'] = obj_orig
  4084. try:
  4085. new_elem['follow'] = obj_orig.exterior
  4086. except AttributeError:
  4087. pass
  4088. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  4089. apertures[str(apid)]['size'] = 0.0
  4090. apertures[str(apid)]['type'] = 'C'
  4091. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4092. obj_init.apertures = deepcopy(apertures)
  4093. def initialize_excellon(obj_init, app):
  4094. apertures = {}
  4095. apid = 10
  4096. for tool in obj.tools:
  4097. apertures[str(apid)] = {}
  4098. apertures[str(apid)]['geometry'] = []
  4099. for geo in obj.tools[tool]['solid_geometry']:
  4100. new_el = {}
  4101. new_el['solid'] = geo
  4102. new_el['follow'] = geo.exterior
  4103. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  4104. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  4105. apertures[str(apid)]['type'] = 'C'
  4106. apid += 1
  4107. # create solid_geometry
  4108. solid_geometry = []
  4109. for apid in apertures:
  4110. for geo_el in apertures[apid]['geometry']:
  4111. solid_geometry.append(geo_el['solid'])
  4112. solid_geometry = MultiPolygon(solid_geometry)
  4113. solid_geometry = solid_geometry.buffer(0.0000001)
  4114. obj_init.solid_geometry = deepcopy(solid_geometry)
  4115. obj_init.apertures = deepcopy(apertures)
  4116. # clear the working objects (perhaps not necessary due of Python GC)
  4117. apertures.clear()
  4118. if not self.collection.get_selected():
  4119. log.warning("App.convert_any2gerber --> No object selected")
  4120. self.inform.emit('[WARNING_NOTCL] %s' %
  4121. _("No object is selected. Select an object and try again."))
  4122. return
  4123. for obj in self.collection.get_selected():
  4124. obj_name = obj.options["name"]
  4125. try:
  4126. if isinstance(obj, ExcellonObject):
  4127. self.app_obj.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  4128. elif isinstance(obj, GeometryObject):
  4129. self.app_obj.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  4130. else:
  4131. log.warning("App.convert_any2gerber --> This is no vaild object for conversion.")
  4132. except Exception as e:
  4133. return "Operation failed: %s" % str(e)
  4134. def abort_all_tasks(self):
  4135. """
  4136. Executed when a certain key combo is pressed (Ctrl+Alt+X). Will abort current task
  4137. on the first possible occasion.
  4138. :return:
  4139. """
  4140. if self.abort_flag is False:
  4141. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  4142. self.abort_flag = True
  4143. self.cleanup.emit()
  4144. def app_is_idle(self):
  4145. if self.abort_flag:
  4146. self.inform.emit('[WARNING_NOTCL] %s' % _("The current task was gracefully closed on user request..."))
  4147. self.abort_flag = False
  4148. def on_selectall(self):
  4149. """
  4150. Will draw a selection box shape around the selected objects.
  4151. :return:
  4152. """
  4153. self.defaults.report_usage("on_selectall()")
  4154. # delete the possible selection box around a possible selected object
  4155. self.delete_selection_shape()
  4156. for name in self.collection.get_names():
  4157. self.collection.set_active(name)
  4158. curr_sel_obj = self.collection.get_by_name(name)
  4159. # create the selection box around the selected object
  4160. if self.defaults['global_selection_shape'] is True:
  4161. self.draw_selection_shape(curr_sel_obj)
  4162. def on_preferences(self):
  4163. """
  4164. Adds the Preferences in a Tab in Plot Area
  4165. :return:
  4166. """
  4167. # add the tab if it was closed
  4168. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  4169. # delete the absolute and relative position and messages in the infobar
  4170. self.ui.position_label.setText("")
  4171. # self.ui.rel_position_label.setText("")
  4172. # Switch plot_area to preferences page
  4173. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  4174. # self.ui.show()
  4175. # detect changes in the preferences
  4176. for idx in range(self.ui.pref_tab_area.count()):
  4177. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  4178. try:
  4179. try:
  4180. tb.textEdited.disconnect(self.preferencesUiManager.on_preferences_edited)
  4181. except (TypeError, AttributeError):
  4182. pass
  4183. tb.textEdited.connect(self.preferencesUiManager.on_preferences_edited)
  4184. except AttributeError:
  4185. pass
  4186. try:
  4187. try:
  4188. tb.modificationChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4189. except (TypeError, AttributeError):
  4190. pass
  4191. tb.modificationChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4192. except AttributeError:
  4193. pass
  4194. try:
  4195. try:
  4196. tb.toggled.disconnect(self.preferencesUiManager.on_preferences_edited)
  4197. except (TypeError, AttributeError):
  4198. pass
  4199. tb.toggled.connect(self.preferencesUiManager.on_preferences_edited)
  4200. except AttributeError:
  4201. pass
  4202. try:
  4203. try:
  4204. tb.valueChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4205. except (TypeError, AttributeError):
  4206. pass
  4207. tb.valueChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4208. except AttributeError:
  4209. pass
  4210. try:
  4211. try:
  4212. tb.currentIndexChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4213. except (TypeError, AttributeError):
  4214. pass
  4215. tb.currentIndexChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4216. except AttributeError:
  4217. pass
  4218. def on_tools_database(self, source='app'):
  4219. """
  4220. Adds the Tools Database in a Tab in Plot Area.
  4221. :return:
  4222. """
  4223. for idx in range(self.ui.plot_tab_area.count()):
  4224. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4225. # there can be only one instance of Tools Database at one time
  4226. return
  4227. if source == 'app':
  4228. self.tools_db_tab = ToolsDB2(
  4229. app=self,
  4230. parent=self.ui,
  4231. callback_on_edited=self.on_tools_db_edited,
  4232. callback_on_tool_request=self.on_geometry_tool_add_from_db_executed
  4233. )
  4234. elif source == 'ncc':
  4235. self.tools_db_tab = ToolsDB2(
  4236. app=self,
  4237. parent=self.ui,
  4238. callback_on_edited=self.on_tools_db_edited,
  4239. callback_on_tool_request=self.ncclear_tool.on_ncc_tool_add_from_db_executed
  4240. )
  4241. elif source == 'paint':
  4242. self.tools_db_tab = ToolsDB2(
  4243. app=self,
  4244. parent=self.ui,
  4245. callback_on_edited=self.on_tools_db_edited,
  4246. callback_on_tool_request=self.paint_tool.on_paint_tool_add_from_db_executed
  4247. )
  4248. # add the tab if it was closed
  4249. try:
  4250. self.ui.plot_tab_area.addTab(self.tools_db_tab, _("Tools Database"))
  4251. self.tools_db_tab.setObjectName("database_tab")
  4252. except Exception as e:
  4253. log.debug("App.on_tools_database() --> %s" % str(e))
  4254. return
  4255. # delete the absolute and relative position and messages in the infobar
  4256. self.ui.position_label.setText("")
  4257. # self.ui.rel_position_label.setText("")
  4258. # Switch plot_area to preferences page
  4259. self.ui.plot_tab_area.setCurrentWidget(self.tools_db_tab)
  4260. # detect changes in the Tools in Tools DB, connect signals from table widget in tab
  4261. self.tools_db_tab.ui_connect()
  4262. def on_tools_db_edited(self):
  4263. """
  4264. Executed whenever a tool is edited in Tools Database.
  4265. Will color the text of the Tools Database tab to Red color.
  4266. :return:
  4267. """
  4268. self.inform.emit('[WARNING_NOTCL] %s' % _("Tools in Tools Database edited but not saved."))
  4269. for idx in range(self.ui.plot_tab_area.count()):
  4270. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4271. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  4272. self.tools_db_tab.save_db_btn.setStyleSheet("QPushButton {color: red;}")
  4273. self.tools_db_changed_flag = True
  4274. def on_geometry_tool_add_from_db_executed(self, tool):
  4275. """
  4276. Here add the tool from DB in the selected geometry object.
  4277. :return:
  4278. """
  4279. tool_from_db = deepcopy(tool)
  4280. obj = self.collection.get_active()
  4281. if isinstance(obj, GeometryObject):
  4282. obj.on_tool_from_db_inserted(tool=tool_from_db)
  4283. # close the tab and delete it
  4284. for idx in range(self.ui.plot_tab_area.count()):
  4285. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4286. wdg = self.ui.plot_tab_area.widget(idx)
  4287. wdg.deleteLater()
  4288. self.ui.plot_tab_area.removeTab(idx)
  4289. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  4290. else:
  4291. self.inform.emit('[ERROR_NOTCL] %s' % _("Adding tool from DB is not allowed for this object."))
  4292. def on_plot_area_tab_closed(self, tab_obj_name):
  4293. """
  4294. Executed whenever a QTab is closed in the Plot Area.
  4295. :param tab_obj_name: The objectName of the Tab that was closed. This objectName is assigned on Tab creation
  4296. :return:
  4297. """
  4298. if tab_obj_name == "preferences_tab":
  4299. self.preferencesUiManager.on_close_preferences_tab()
  4300. elif tab_obj_name == "database_tab":
  4301. # disconnect the signals from the table widget in tab
  4302. self.tools_db_tab.ui_disconnect()
  4303. if self.tools_db_changed_flag is True:
  4304. msgbox = QtWidgets.QMessageBox()
  4305. msgbox.setText(_("One or more Tools are edited.\n"
  4306. "Do you want to update the Tools Database?"))
  4307. msgbox.setWindowTitle(_("Save Tools Database"))
  4308. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  4309. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  4310. msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  4311. msgbox.setDefaultButton(bt_yes)
  4312. msgbox.exec_()
  4313. response = msgbox.clickedButton()
  4314. if response == bt_yes:
  4315. self.tools_db_tab.on_save_tools_db()
  4316. self.inform.emit('[success] %s' % "Tools DB saved to file.")
  4317. else:
  4318. self.tools_db_changed_flag = False
  4319. self.inform.emit('')
  4320. return
  4321. self.tools_db_tab.deleteLater()
  4322. elif tab_obj_name == "text_editor_tab":
  4323. self.toggle_codeeditor = False
  4324. elif tab_obj_name == "bookmarks_tab":
  4325. self.book_dialog_tab.rebuild_actions()
  4326. self.book_dialog_tab.deleteLater()
  4327. else:
  4328. return
  4329. # def on_plotarea_tab_closed(self, tab_idx):
  4330. # """
  4331. #
  4332. # :param tab_idx: Index of the Tab from the plotarea that was closed
  4333. # :return:
  4334. # """
  4335. # widget = self.ui.plot_tab_area.widget(tab_idx)
  4336. #
  4337. # if widget is not None:
  4338. # widget.deleteLater()
  4339. # self.ui.plot_tab_area.removeTab(tab_idx)
  4340. def on_flipy(self):
  4341. """
  4342. Executed when the menu entry in Options -> Flip on Y axis is clicked.
  4343. :return:
  4344. """
  4345. self.defaults.report_usage("on_flipy()")
  4346. obj_list = self.collection.get_selected()
  4347. xminlist = []
  4348. yminlist = []
  4349. xmaxlist = []
  4350. ymaxlist = []
  4351. if not obj_list:
  4352. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Flip on Y axis."))
  4353. else:
  4354. try:
  4355. # first get a bounding box to fit all
  4356. for obj in obj_list:
  4357. xmin, ymin, xmax, ymax = obj.bounds()
  4358. xminlist.append(xmin)
  4359. yminlist.append(ymin)
  4360. xmaxlist.append(xmax)
  4361. ymaxlist.append(ymax)
  4362. # get the minimum x,y and maximum x,y for all objects selected
  4363. xminimal = min(xminlist)
  4364. yminimal = min(yminlist)
  4365. xmaximal = max(xmaxlist)
  4366. ymaximal = max(ymaxlist)
  4367. px = 0.5 * (xminimal + xmaximal)
  4368. py = 0.5 * (yminimal + ymaximal)
  4369. # execute mirroring
  4370. for obj in obj_list:
  4371. obj.mirror('X', [px, py])
  4372. obj.plot()
  4373. self.app_obj.object_changed.emit(obj)
  4374. self.inform.emit('[success] %s' %
  4375. _("Flip on Y axis done."))
  4376. except Exception as e:
  4377. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  4378. return
  4379. def on_flipx(self):
  4380. """
  4381. Executed when the menu entry in Options -> Flip on X axis is clicked.
  4382. :return:
  4383. """
  4384. self.defaults.report_usage("on_flipx()")
  4385. obj_list = self.collection.get_selected()
  4386. xminlist = []
  4387. yminlist = []
  4388. xmaxlist = []
  4389. ymaxlist = []
  4390. if not obj_list:
  4391. self.inform.emit('[WARNING_NOTCL] %s' %
  4392. _("No object selected to Flip on X axis."))
  4393. else:
  4394. try:
  4395. # first get a bounding box to fit all
  4396. for obj in obj_list:
  4397. xmin, ymin, xmax, ymax = obj.bounds()
  4398. xminlist.append(xmin)
  4399. yminlist.append(ymin)
  4400. xmaxlist.append(xmax)
  4401. ymaxlist.append(ymax)
  4402. # get the minimum x,y and maximum x,y for all objects selected
  4403. xminimal = min(xminlist)
  4404. yminimal = min(yminlist)
  4405. xmaximal = max(xmaxlist)
  4406. ymaximal = max(ymaxlist)
  4407. px = 0.5 * (xminimal + xmaximal)
  4408. py = 0.5 * (yminimal + ymaximal)
  4409. # execute mirroring
  4410. for obj in obj_list:
  4411. obj.mirror('Y', [px, py])
  4412. obj.plot()
  4413. self.app_obj.object_changed.emit(obj)
  4414. self.inform.emit('[success] %s' %
  4415. _("Flip on X axis done."))
  4416. except Exception as e:
  4417. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  4418. return
  4419. def on_rotate(self, silent=False, preset=None):
  4420. """
  4421. Executed when Options -> Rotate Selection menu entry is clicked.
  4422. :param silent: If silent is True then use the preset value for the angle of the rotation.
  4423. :param preset: A value to be used as predefined angle for rotation.
  4424. :return:
  4425. """
  4426. self.defaults.report_usage("on_rotate()")
  4427. obj_list = self.collection.get_selected()
  4428. xminlist = []
  4429. yminlist = []
  4430. xmaxlist = []
  4431. ymaxlist = []
  4432. if not obj_list:
  4433. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Rotate."))
  4434. else:
  4435. if silent is False:
  4436. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4437. min=-360, max=360, decimals=4,
  4438. init_val=float(self.defaults['tools_transform_rotate']))
  4439. num, ok = rotatebox.get_value()
  4440. else:
  4441. num = preset
  4442. ok = True
  4443. if ok:
  4444. try:
  4445. # first get a bounding box to fit all
  4446. for obj in obj_list:
  4447. xmin, ymin, xmax, ymax = obj.bounds()
  4448. xminlist.append(xmin)
  4449. yminlist.append(ymin)
  4450. xmaxlist.append(xmax)
  4451. ymaxlist.append(ymax)
  4452. # get the minimum x,y and maximum x,y for all objects selected
  4453. xminimal = min(xminlist)
  4454. yminimal = min(yminlist)
  4455. xmaximal = max(xmaxlist)
  4456. ymaximal = max(ymaxlist)
  4457. px = 0.5 * (xminimal + xmaximal)
  4458. py = 0.5 * (yminimal + ymaximal)
  4459. for sel_obj in obj_list:
  4460. sel_obj.rotate(-float(num), point=(px, py))
  4461. sel_obj.plot()
  4462. self.app_obj.object_changed.emit(sel_obj)
  4463. self.inform.emit('[success] %s' % _("Rotation done."))
  4464. except Exception as e:
  4465. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Rotation movement was not executed."), str(e)))
  4466. return
  4467. def on_skewx(self):
  4468. """
  4469. Executed when the menu entry in Options -> Skew on X axis is clicked.
  4470. :return:
  4471. """
  4472. self.defaults.report_usage("on_skewx()")
  4473. obj_list = self.collection.get_selected()
  4474. xminlist = []
  4475. yminlist = []
  4476. if not obj_list:
  4477. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Skew/Shear on X axis."))
  4478. else:
  4479. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4480. min=-360, max=360, decimals=4,
  4481. init_val=float(self.defaults['tools_transform_skew_x']))
  4482. num, ok = skewxbox.get_value()
  4483. if ok:
  4484. # first get a bounding box to fit all
  4485. for obj in obj_list:
  4486. xmin, ymin, xmax, ymax = obj.bounds()
  4487. xminlist.append(xmin)
  4488. yminlist.append(ymin)
  4489. # get the minimum x,y and maximum x,y for all objects selected
  4490. xminimal = min(xminlist)
  4491. yminimal = min(yminlist)
  4492. for obj in obj_list:
  4493. obj.skew(num, 0, point=(xminimal, yminimal))
  4494. obj.plot()
  4495. self.app_obj.object_changed.emit(obj)
  4496. self.inform.emit('[success] %s' % _("Skew on X axis done."))
  4497. def on_skewy(self):
  4498. """
  4499. Executed when the menu entry in Options -> Skew on Y axis is clicked.
  4500. :return:
  4501. """
  4502. self.defaults.report_usage("on_skewy()")
  4503. obj_list = self.collection.get_selected()
  4504. xminlist = []
  4505. yminlist = []
  4506. if not obj_list:
  4507. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Skew/Shear on Y axis."))
  4508. else:
  4509. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4510. min=-360, max=360, decimals=4,
  4511. init_val=float(self.defaults['tools_transform_skew_y']))
  4512. num, ok = skewybox.get_value()
  4513. if ok:
  4514. # first get a bounding box to fit all
  4515. for obj in obj_list:
  4516. xmin, ymin, xmax, ymax = obj.bounds()
  4517. xminlist.append(xmin)
  4518. yminlist.append(ymin)
  4519. # get the minimum x,y and maximum x,y for all objects selected
  4520. xminimal = min(xminlist)
  4521. yminimal = min(yminlist)
  4522. for obj in obj_list:
  4523. obj.skew(0, num, point=(xminimal, yminimal))
  4524. obj.plot()
  4525. self.app_obj.object_changed.emit(obj)
  4526. self.inform.emit('[success] %s' % _("Skew on Y axis done."))
  4527. def on_plots_updated(self):
  4528. """
  4529. Callback used to report when the plots have changed.
  4530. Adjust axes and zooms to fit.
  4531. :return: None
  4532. """
  4533. if self.is_legacy is False:
  4534. self.plotcanvas.update()
  4535. else:
  4536. self.plotcanvas.auto_adjust_axes()
  4537. self.on_zoom_fit()
  4538. self.collection.update_view()
  4539. # self.inform.emit(_("Plots updated ..."))
  4540. def on_toolbar_replot(self):
  4541. """
  4542. Callback for toolbar button. Re-plots all objects.
  4543. :return: None
  4544. """
  4545. self.defaults.report_usage("on_toolbar_replot")
  4546. self.log.debug("on_toolbar_replot()")
  4547. try:
  4548. self.collection.get_active().read_form()
  4549. except AttributeError:
  4550. self.log.debug("on_toolbar_replot(): AttributeError")
  4551. pass
  4552. self.plot_all()
  4553. def grid_status(self):
  4554. return True if self.ui.grid_snap_btn.isChecked() else False
  4555. def populate_cmenu_grids(self):
  4556. units = self.defaults['units'].lower()
  4557. # for act in self.ui.cmenu_gridmenu.actions():
  4558. # act.triggered.disconnect()
  4559. self.ui.cmenu_gridmenu.clear()
  4560. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  4561. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  4562. _("Grid On/Off"))
  4563. grid_toggle.setCheckable(True)
  4564. grid_toggle.setChecked(True) if self.grid_status() else grid_toggle.setChecked(False)
  4565. self.ui.cmenu_gridmenu.addSeparator()
  4566. for grid in sorted_list:
  4567. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  4568. "%s" % str(grid))
  4569. action.triggered.connect(self.set_grid)
  4570. self.ui.cmenu_gridmenu.addSeparator()
  4571. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/plus32.png'),
  4572. _("Add"))
  4573. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/delete32.png'),
  4574. _("Delete"))
  4575. grid_add.triggered.connect(self.on_grid_add)
  4576. grid_delete.triggered.connect(self.on_grid_delete)
  4577. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  4578. def set_grid(self):
  4579. menu_action = self.sender()
  4580. assert isinstance(menu_action, QtWidgets.QAction), "Expected QAction got %s" % type(menu_action)
  4581. self.ui.grid_gap_x_entry.setText(menu_action.text())
  4582. self.ui.grid_gap_y_entry.setText(menu_action.text())
  4583. def on_grid_add(self):
  4584. # ## Current application units in lower Case
  4585. units = self.defaults['units'].lower()
  4586. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  4587. text=_('Enter a Grid Value:'),
  4588. min=0.0000, max=99.9999, decimals=4)
  4589. grid_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/plus32.png'))
  4590. val, ok = grid_add_popup.get_value()
  4591. if ok:
  4592. if float(val) == 0:
  4593. self.inform.emit('[WARNING_NOTCL] %s' %
  4594. _("Please enter a grid value with non-zero value, in Float format."))
  4595. return
  4596. else:
  4597. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  4598. self.defaults["global_grid_context_menu"][str(units)].append(val)
  4599. self.inform.emit('[success] %s...' % _("New Grid added"))
  4600. else:
  4601. self.inform.emit('[WARNING_NOTCL] %s...' % _("Grid already exists"))
  4602. else:
  4603. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding New Grid cancelled"))
  4604. def on_grid_delete(self):
  4605. # ## Current application units in lower Case
  4606. units = self.defaults['units'].lower()
  4607. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  4608. text='Enter a Grid Value:',
  4609. min=0.0000, max=99.9999, decimals=4)
  4610. grid_del_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/delete32.png'))
  4611. val, ok = grid_del_popup.get_value()
  4612. if ok:
  4613. if float(val) == 0:
  4614. self.inform.emit('[WARNING_NOTCL] %s' %
  4615. _("Please enter a grid value with non-zero value, in Float format."))
  4616. return
  4617. else:
  4618. try:
  4619. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  4620. except ValueError:
  4621. self.inform.emit('[ERROR_NOTCL]%s...' % _(" Grid Value does not exist"))
  4622. return
  4623. self.inform.emit('[success] %s...' % _("Grid Value deleted"))
  4624. else:
  4625. self.inform.emit('[WARNING_NOTCL] %s...' % _("Delete Grid value cancelled"))
  4626. def on_shortcut_list(self):
  4627. self.defaults.report_usage("on_shortcut_list()")
  4628. # add the tab if it was closed
  4629. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  4630. # delete the absolute and relative position and messages in the infobar
  4631. self.ui.position_label.setText("")
  4632. # self.ui.rel_position_label.setText("")
  4633. # Switch plot_area to preferences page
  4634. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  4635. # self.ui.show()
  4636. def on_select_tab(self, name):
  4637. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  4638. if self.ui.splitter.sizes()[0] == 0:
  4639. self.ui.splitter.setSizes([1, 1])
  4640. else:
  4641. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  4642. self.ui.splitter.setSizes([0, 1])
  4643. if name == 'project':
  4644. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  4645. elif name == 'selected':
  4646. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  4647. elif name == 'tool':
  4648. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  4649. def on_copy_name(self):
  4650. self.defaults.report_usage("on_copy_name()")
  4651. obj = self.collection.get_active()
  4652. try:
  4653. name = obj.options["name"]
  4654. except AttributeError:
  4655. log.debug("on_copy_name() --> No object selected to copy it's name")
  4656. self.inform.emit('[WARNING_NOTCL]%s' %
  4657. _(" No object selected to copy it's name"))
  4658. return
  4659. self.clipboard.setText(name)
  4660. self.inform.emit(_("Name copied on clipboard ..."))
  4661. def on_mouse_click_over_plot(self, event):
  4662. """
  4663. Default actions are:
  4664. :param event: Contains information about the event, like which button
  4665. was clicked, the pixel coordinates and the axes coordinates.
  4666. :return: None
  4667. """
  4668. self.pos = []
  4669. if self.is_legacy is False:
  4670. event_pos = event.pos
  4671. # pan_button = 2 if self.defaults["global_pan_button"] == '2'else 3
  4672. # # Set the mouse button for panning
  4673. # self.plotcanvas.view.camera.pan_button_setting = pan_button
  4674. else:
  4675. event_pos = (event.xdata, event.ydata)
  4676. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  4677. # pan_button = 3 if self.defaults["global_pan_button"] == '2' else 2
  4678. # So it can receive key presses
  4679. self.plotcanvas.native.setFocus()
  4680. self.pos_canvas = self.plotcanvas.translate_coords(event_pos)
  4681. if self.grid_status():
  4682. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  4683. else:
  4684. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  4685. try:
  4686. if event.button == 1:
  4687. # Reset here the relative coordinates so there is a new reference on the click position
  4688. if self.rel_point1 is None:
  4689. self.rel_point1 = self.pos
  4690. else:
  4691. self.rel_point2 = copy(self.rel_point1)
  4692. self.rel_point1 = self.pos
  4693. self.on_mouse_move_over_plot(event, origin_click=True)
  4694. except Exception as e:
  4695. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  4696. def on_mouse_double_click_over_plot(self, event):
  4697. if event.button == 1:
  4698. self.doubleclick = True
  4699. def on_mouse_move_over_plot(self, event, origin_click=None):
  4700. """
  4701. Callback for the mouse motion event over the plot.
  4702. :param event: Contains information about the event.
  4703. :param origin_click
  4704. :return: None
  4705. """
  4706. if self.is_legacy is False:
  4707. event_pos = event.pos
  4708. if self.defaults["global_pan_button"] == '2':
  4709. pan_button = 2
  4710. else:
  4711. pan_button = 3
  4712. self.event_is_dragging = event.is_dragging
  4713. else:
  4714. event_pos = (event.xdata, event.ydata)
  4715. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  4716. if self.defaults["global_pan_button"] == '2':
  4717. pan_button = 3
  4718. else:
  4719. pan_button = 2
  4720. self.event_is_dragging = self.plotcanvas.is_dragging
  4721. # So it can receive key presses but not when the Tcl Shell is active
  4722. if not self.ui.shell_dock.isVisible():
  4723. if not self.plotcanvas.native.hasFocus():
  4724. self.plotcanvas.native.setFocus()
  4725. self.pos_jump = event_pos
  4726. self.ui.popMenu.mouse_is_panning = False
  4727. if origin_click is None:
  4728. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  4729. if event.button == pan_button and self.event_is_dragging == 1:
  4730. # if a popup menu is active don't change mouse_is_panning variable because is not True
  4731. if self.ui.popMenu.popup_active:
  4732. self.ui.popMenu.popup_active = False
  4733. return
  4734. self.ui.popMenu.mouse_is_panning = True
  4735. return
  4736. if self.rel_point1 is not None:
  4737. try: # May fail in case mouse not within axes
  4738. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  4739. if pos_canvas[0] is None or pos_canvas[1] is None:
  4740. return
  4741. if self.grid_status():
  4742. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  4743. # Update cursor
  4744. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  4745. symbol='++', edge_color=self.cursor_color_3D,
  4746. edge_width=self.defaults["global_cursor_width"],
  4747. size=self.defaults["global_cursor_size"])
  4748. else:
  4749. pos = (pos_canvas[0], pos_canvas[1])
  4750. self.dx = pos[0] - float(self.rel_point1[0])
  4751. self.dy = pos[1] - float(self.rel_point1[1])
  4752. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4753. "<b>Y</b>: %.4f&nbsp;" % (pos[0], pos[1]))
  4754. # self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4755. # "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  4756. units = self.defaults["units"].lower()
  4757. self.plotcanvas.text_hud.text = \
  4758. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  4759. self.dx, units, self.dy, units, pos[0], units, pos[1], units)
  4760. self.mouse = [pos[0], pos[1]]
  4761. # if the mouse is moved and the LMB is clicked then the action is a selection
  4762. if self.event_is_dragging == 1 and event.button == 1:
  4763. self.delete_selection_shape()
  4764. if self.dx < 0:
  4765. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  4766. face_color=self.defaults['global_alt_sel_fill'])
  4767. self.selection_type = False
  4768. elif self.dx >= 0:
  4769. self.draw_moving_selection_shape(self.pos, pos)
  4770. self.selection_type = True
  4771. else:
  4772. self.selection_type = None
  4773. else:
  4774. self.selection_type = None
  4775. # hover effect - enabled in Preferences -> General -> AppGUI Settings
  4776. if self.defaults['global_hover']:
  4777. for obj in self.collection.get_list():
  4778. try:
  4779. # select the object(s) only if it is enabled (plotted)
  4780. if obj.options['plot']:
  4781. if obj not in self.collection.get_selected():
  4782. poly_obj = Polygon(
  4783. [(obj.options['xmin'], obj.options['ymin']),
  4784. (obj.options['xmax'], obj.options['ymin']),
  4785. (obj.options['xmax'], obj.options['ymax']),
  4786. (obj.options['xmin'], obj.options['ymax'])]
  4787. )
  4788. if Point(pos).within(poly_obj):
  4789. if obj.isHovering is False:
  4790. obj.isHovering = True
  4791. obj.notHovering = True
  4792. # create the selection box around the selected object
  4793. self.draw_hover_shape(obj, color='#d1e0e0FF')
  4794. else:
  4795. if obj.notHovering is True:
  4796. obj.notHovering = False
  4797. obj.isHovering = False
  4798. self.delete_hover_shape()
  4799. except Exception:
  4800. # the Exception here will happen if we try to select on screen and we have an
  4801. # newly (and empty) just created Geometry or Excellon object that do not have the
  4802. # xmin, xmax, ymin, ymax options.
  4803. # In this case poly_obj creation (see above) will fail
  4804. pass
  4805. except Exception as e:
  4806. log.debug("App.on_mouse_move_over_plot() - rel_point1 is not None -> %s" % str(e))
  4807. self.ui.position_label.setText("")
  4808. # self.ui.rel_position_label.setText("")
  4809. self.mouse = None
  4810. def on_mouse_click_release_over_plot(self, event):
  4811. """
  4812. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  4813. and has been registered in ''self.__init__()''.
  4814. :param event: contains information about the event.
  4815. :return:
  4816. """
  4817. if self.is_legacy is False:
  4818. event_pos = event.pos
  4819. right_button = 2
  4820. else:
  4821. event_pos = (event.xdata, event.ydata)
  4822. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  4823. right_button = 3
  4824. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  4825. if self.grid_status():
  4826. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  4827. else:
  4828. pos = (pos_canvas[0], pos_canvas[1])
  4829. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  4830. # canvas menu
  4831. if event.button == right_button and self.ui.popMenu.mouse_is_panning is False: # right click
  4832. self.ui.popMenu.mouse_is_panning = False
  4833. self.cursor = QtGui.QCursor()
  4834. self.populate_cmenu_grids()
  4835. self.ui.popMenu.popup(self.cursor.pos())
  4836. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  4837. # selection and then select a type of selection ("enclosing" or "touching")
  4838. if event.button == 1: # left click
  4839. modifiers = QtWidgets.QApplication.keyboardModifiers()
  4840. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  4841. if modifiers == QtCore.Qt.ShiftModifier:
  4842. # do not auto open the Project Tab
  4843. self.click_noproject = True
  4844. self.clipboard.setText(
  4845. self.defaults["global_point_clipboard_format"] %
  4846. (self.decimals, self.pos[0], self.decimals, self.pos[1])
  4847. )
  4848. self.inform.emit('[success] %s' % _("Coordinates copied to clipboard."))
  4849. return
  4850. if self.doubleclick is True:
  4851. self.doubleclick = False
  4852. if self.collection.get_selected():
  4853. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  4854. if self.ui.splitter.sizes()[0] == 0:
  4855. self.ui.splitter.setSizes([1, 1])
  4856. try:
  4857. # delete the selection shape(S) as it may be in the way
  4858. self.delete_selection_shape()
  4859. self.delete_hover_shape()
  4860. except Exception as e:
  4861. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() double click --> Error: %s" % str(e))
  4862. return
  4863. else:
  4864. # WORKAROUND for LEGACY MODE
  4865. if self.is_legacy is True:
  4866. # if there is no move on canvas then we have no dragging selection
  4867. if self.dx == 0 or self.dy == 0:
  4868. self.selection_type = None
  4869. if self.selection_type is not None:
  4870. try:
  4871. self.selection_area_handler(self.pos, pos, self.selection_type)
  4872. self.selection_type = None
  4873. except Exception as e:
  4874. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select area --> Error: %s" % str(e))
  4875. return
  4876. else:
  4877. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  4878. if key_modifier == QtCore.Qt.ShiftModifier:
  4879. mod_key = 'Shift'
  4880. elif key_modifier == QtCore.Qt.ControlModifier:
  4881. mod_key = 'Control'
  4882. else:
  4883. mod_key = None
  4884. try:
  4885. if self.command_active is None:
  4886. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  4887. # deselect, and if it's not selected then it will be selected
  4888. # If there is no active command (self.command_active is None) then we check if we clicked
  4889. # on a object by checking the bounding limits against mouse click position
  4890. if mod_key == self.defaults["global_mselect_key"]:
  4891. self.select_objects(key='multisel')
  4892. else:
  4893. # If there is no active command (self.command_active is None) then we check if
  4894. # we clicked on a object by checking the bounding limits against mouse click position
  4895. self.select_objects()
  4896. self.delete_hover_shape()
  4897. except Exception as e:
  4898. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select click --> Error: %s" % str(e))
  4899. return
  4900. def selection_area_handler(self, start_pos, end_pos, sel_type):
  4901. """
  4902. :param start_pos: mouse position when the selection LMB click was done
  4903. :param end_pos: mouse position when the left mouse button is released
  4904. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  4905. :return:
  4906. """
  4907. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  4908. # delete previous selection shape
  4909. self.delete_selection_shape()
  4910. # make all objects inactive
  4911. self.collection.set_all_inactive()
  4912. for obj in self.collection.get_list():
  4913. try:
  4914. # select the object(s) only if it is enabled (plotted)
  4915. if obj.options['plot']:
  4916. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  4917. (obj.options['xmax'], obj.options['ymin']),
  4918. (obj.options['xmax'], obj.options['ymax']),
  4919. (obj.options['xmin'], obj.options['ymax'])])
  4920. if sel_type is True:
  4921. if poly_obj.within(poly_selection):
  4922. # create the selection box around the selected object
  4923. if self.defaults['global_selection_shape'] is True:
  4924. self.draw_selection_shape(obj)
  4925. self.collection.set_active(obj.options['name'])
  4926. else:
  4927. if poly_selection.intersects(poly_obj):
  4928. # create the selection box around the selected object
  4929. if self.defaults['global_selection_shape'] is True:
  4930. self.draw_selection_shape(obj)
  4931. self.collection.set_active(obj.options['name'])
  4932. obj.selection_shape_drawn = True
  4933. except Exception as e:
  4934. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  4935. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  4936. # In this case poly_obj creation (see above) will fail
  4937. log.debug("App.selection_area_handler() --> %s" % str(e))
  4938. def select_objects(self, key=None):
  4939. """
  4940. Will select objects clicked on canvas
  4941. :param key: for future use in cumulative selection
  4942. :return:
  4943. """
  4944. # list where we store the overlapped objects under our mouse left click position
  4945. if key is None:
  4946. self.objects_under_the_click_list = []
  4947. # Populate the list with the overlapped objects on the click position
  4948. curr_x, curr_y = self.pos
  4949. for obj in self.all_objects_list:
  4950. # ScriptObject and DocumentObject objects can't be selected
  4951. if obj.kind == 'script' or obj.kind == 'document':
  4952. continue
  4953. if key == 'multisel' and obj.options['name'] in self.objects_under_the_click_list:
  4954. continue
  4955. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  4956. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  4957. if obj.options['name'] not in self.objects_under_the_click_list:
  4958. if obj.options['plot']:
  4959. # add objects to the objects_under_the_click list only if the object is plotted
  4960. # (active and not disabled)
  4961. self.objects_under_the_click_list.append(obj.options['name'])
  4962. try:
  4963. if self.objects_under_the_click_list:
  4964. curr_sel_obj = self.collection.get_active()
  4965. # case when there is only an object under the click and we toggle it
  4966. if len(self.objects_under_the_click_list) == 1:
  4967. if curr_sel_obj is None:
  4968. self.collection.set_active(self.objects_under_the_click_list[0])
  4969. curr_sel_obj = self.collection.get_active()
  4970. # create the selection box around the selected object
  4971. if self.defaults['global_selection_shape'] is True:
  4972. self.draw_selection_shape(curr_sel_obj)
  4973. curr_sel_obj.selection_shape_drawn = True
  4974. elif curr_sel_obj.options['name'] not in self.objects_under_the_click_list:
  4975. self.collection.on_objects_selection(False)
  4976. self.delete_selection_shape()
  4977. curr_sel_obj.selection_shape_drawn = False
  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. self.selected_message(curr_sel_obj=curr_sel_obj)
  4985. elif curr_sel_obj.selection_shape_drawn is False:
  4986. if self.defaults['global_selection_shape'] is True:
  4987. self.draw_selection_shape(curr_sel_obj)
  4988. curr_sel_obj.selection_shape_drawn = True
  4989. else:
  4990. self.collection.on_objects_selection(False)
  4991. self.delete_selection_shape()
  4992. if self.call_source != 'app':
  4993. self.call_source = 'app'
  4994. self.selected_message(curr_sel_obj=curr_sel_obj)
  4995. else:
  4996. # If there is no selected object
  4997. # make active the first element of the overlapped objects list
  4998. if self.collection.get_active() is None:
  4999. self.collection.set_active(self.objects_under_the_click_list[0])
  5000. self.collection.get_by_name(self.objects_under_the_click_list[0]).selection_shape_drawn = True
  5001. name_sel_obj = self.collection.get_active().options['name']
  5002. # In case that there is a selected object but it is not in the overlapped object list
  5003. # make that object inactive and activate the first element in the overlapped object list
  5004. if name_sel_obj not in self.objects_under_the_click_list:
  5005. self.collection.set_inactive(name_sel_obj)
  5006. name_sel_obj = self.objects_under_the_click_list[0]
  5007. self.collection.set_active(name_sel_obj)
  5008. else:
  5009. sel_idx = self.objects_under_the_click_list.index(name_sel_obj)
  5010. self.collection.set_all_inactive()
  5011. self.collection.set_active(
  5012. self.objects_under_the_click_list[(sel_idx + 1) % len(self.objects_under_the_click_list)])
  5013. curr_sel_obj = self.collection.get_active()
  5014. # delete the possible selection box around a possible selected object
  5015. self.delete_selection_shape()
  5016. curr_sel_obj.selection_shape_drawn = False
  5017. # create the selection box around the selected object
  5018. if self.defaults['global_selection_shape'] is True:
  5019. self.draw_selection_shape(curr_sel_obj)
  5020. curr_sel_obj.selection_shape_drawn = True
  5021. self.selected_message(curr_sel_obj=curr_sel_obj)
  5022. else:
  5023. # deselect everything
  5024. self.collection.on_objects_selection(False)
  5025. # delete the possible selection box around a possible selected object
  5026. self.delete_selection_shape()
  5027. for o in self.collection.get_list():
  5028. o.selection_shape_drawn = False
  5029. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  5030. # only when working on App
  5031. if self.call_source == 'app':
  5032. if self.click_noproject is False:
  5033. # if the Tool Tab is in focus don't change focus to Project Tab
  5034. if not self.ui.notebook.currentWidget() is self.ui.tool_tab:
  5035. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5036. else:
  5037. # restore auto open the Project Tab
  5038. self.click_noproject = False
  5039. # delete any text in the status bar, implicitly the last object name that was selected
  5040. # self.inform.emit("")
  5041. else:
  5042. self.call_source = 'app'
  5043. except Exception as e:
  5044. log.error("[ERROR] Something went bad in App.select_objects(). %s" % str(e))
  5045. def selected_message(self, curr_sel_obj):
  5046. if curr_sel_obj:
  5047. if curr_sel_obj.kind == 'gerber':
  5048. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5049. color='green',
  5050. name=str(curr_sel_obj.options['name']),
  5051. tx=_("selected"))
  5052. )
  5053. elif curr_sel_obj.kind == 'excellon':
  5054. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5055. color='brown',
  5056. name=str(curr_sel_obj.options['name']),
  5057. tx=_("selected"))
  5058. )
  5059. elif curr_sel_obj.kind == 'cncjob':
  5060. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5061. color='blue',
  5062. name=str(curr_sel_obj.options['name']),
  5063. tx=_("selected"))
  5064. )
  5065. elif curr_sel_obj.kind == 'geometry':
  5066. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5067. color='red',
  5068. name=str(curr_sel_obj.options['name']),
  5069. tx=_("selected"))
  5070. )
  5071. def delete_hover_shape(self):
  5072. self.hover_shapes.clear()
  5073. self.hover_shapes.redraw()
  5074. def draw_hover_shape(self, sel_obj, color=None):
  5075. """
  5076. :param sel_obj: The object for which the hover shape must be drawn
  5077. :param color: The color of the hover shape
  5078. :return: None
  5079. """
  5080. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5081. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5082. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5083. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5084. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  5085. if self.defaults['units'].upper() == 'MM':
  5086. hover_rect = hover_rect.buffer(-0.1)
  5087. hover_rect = hover_rect.buffer(0.2)
  5088. else:
  5089. hover_rect = hover_rect.buffer(-0.00393)
  5090. hover_rect = hover_rect.buffer(0.00787)
  5091. # if color:
  5092. # face = Color(color)
  5093. # face.alpha = 0.2
  5094. # outline = Color(color, alpha=0.8)
  5095. # else:
  5096. # face = Color(self.defaults['global_sel_fill'])
  5097. # face.alpha = 0.2
  5098. # outline = self.defaults['global_sel_line']
  5099. if color:
  5100. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5101. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5102. else:
  5103. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5104. outline = self.defaults['global_sel_line']
  5105. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  5106. if self.is_legacy is True:
  5107. self.hover_shapes.redraw()
  5108. def delete_selection_shape(self):
  5109. self.move_tool.sel_shapes.clear()
  5110. self.move_tool.sel_shapes.redraw()
  5111. def draw_selection_shape(self, sel_obj, color=None):
  5112. """
  5113. Will draw a selection shape around the selected object.
  5114. :param sel_obj: The object for which the selection shape must be drawn
  5115. :param color: The color for the selection shape.
  5116. :return: None
  5117. """
  5118. if sel_obj is None:
  5119. return
  5120. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5121. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5122. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5123. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5124. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5125. if self.defaults['units'].upper() == 'MM':
  5126. sel_rect = sel_rect.buffer(-0.1)
  5127. sel_rect = sel_rect.buffer(0.2)
  5128. else:
  5129. sel_rect = sel_rect.buffer(-0.00393)
  5130. sel_rect = sel_rect.buffer(0.00787)
  5131. if color:
  5132. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5133. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5134. else:
  5135. if self.is_legacy is False:
  5136. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5137. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  5138. else:
  5139. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.4 * 255)))[2:]
  5140. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(1.0 * 255)))[2:]
  5141. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  5142. color=outline,
  5143. face_color=face,
  5144. update=True,
  5145. layer=0,
  5146. tolerance=None))
  5147. if self.is_legacy is True:
  5148. self.move_tool.sel_shapes.redraw()
  5149. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  5150. """
  5151. Will draw a selection shape when dragging mouse on canvas.
  5152. :param old_coords: Old coordinates
  5153. :param coords: New coordinates
  5154. :param kwargs: Keyword arguments
  5155. :return:
  5156. """
  5157. if 'color' in kwargs:
  5158. color = kwargs['color']
  5159. else:
  5160. color = self.defaults['global_sel_line']
  5161. if 'face_color' in kwargs:
  5162. face_color = kwargs['face_color']
  5163. else:
  5164. face_color = self.defaults['global_sel_fill']
  5165. if 'face_alpha' in kwargs:
  5166. face_alpha = kwargs['face_alpha']
  5167. else:
  5168. face_alpha = 0.3
  5169. x0, y0 = old_coords
  5170. x1, y1 = coords
  5171. pt1 = (x0, y0)
  5172. pt2 = (x1, y0)
  5173. pt3 = (x1, y1)
  5174. pt4 = (x0, y1)
  5175. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5176. # color_t = Color(face_color)
  5177. # color_t.alpha = face_alpha
  5178. color_t = face_color[:-2] + str(hex(int(face_alpha * 255)))[2:]
  5179. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  5180. layer=0, tolerance=None)
  5181. if self.is_legacy is True:
  5182. self.move_tool.sel_shapes.redraw()
  5183. def on_file_new_click(self):
  5184. """
  5185. Callback for menu item File -> New.
  5186. Executed on clicking the Menu -> File -> New Project
  5187. :return:
  5188. """
  5189. if self.collection.get_list() and self.should_we_save:
  5190. msgbox = QtWidgets.QMessageBox()
  5191. # msgbox.setText("<B>Save changes ...</B>")
  5192. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  5193. "Creating a New project will delete them.\n"
  5194. "Do you want to Save the project?"))
  5195. msgbox.setWindowTitle(_("Save changes"))
  5196. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  5197. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  5198. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  5199. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  5200. msgbox.setDefaultButton(bt_yes)
  5201. msgbox.exec_()
  5202. response = msgbox.clickedButton()
  5203. if response == bt_yes:
  5204. self.on_file_saveprojectas()
  5205. elif response == bt_cancel:
  5206. return
  5207. elif response == bt_no:
  5208. self.on_file_new()
  5209. else:
  5210. self.on_file_new()
  5211. self.inform.emit('[success] %s...' % _("New Project created"))
  5212. def on_file_new(self, cli=None):
  5213. """
  5214. Returns the application to its startup state. This method is thread-safe.
  5215. :param cli: Boolean. If True this method was run from command line
  5216. :return: None
  5217. """
  5218. self.defaults.report_usage("on_file_new")
  5219. # Remove everything from memory
  5220. App.log.debug("on_file_new()")
  5221. # close any editor that might be open
  5222. if self.call_source != 'app':
  5223. self.editor2object(cleanup=True)
  5224. # ## EDITOR section
  5225. self.geo_editor = FlatCAMGeoEditor(self)
  5226. self.exc_editor = FlatCAMExcEditor(self)
  5227. self.grb_editor = FlatCAMGrbEditor(self)
  5228. # Clear pool
  5229. self.clear_pool()
  5230. for obj in self.collection.get_list():
  5231. # delete shapes left drawn from mark shape_collections, if any
  5232. if isinstance(obj, GerberObject):
  5233. try:
  5234. for el in obj.mark_shapes:
  5235. obj.mark_shapes[el].clear(update=True)
  5236. obj.mark_shapes[el].enabled = False
  5237. del el
  5238. except AttributeError:
  5239. pass
  5240. # also delete annotation shapes, if any
  5241. elif isinstance(obj, CNCJobObject):
  5242. try:
  5243. obj.text_col.enabled = False
  5244. del obj.text_col
  5245. obj.annotation.clear(update=True)
  5246. del obj.annotation
  5247. except AttributeError:
  5248. pass
  5249. # delete the exclusion areas
  5250. self.exc_areas.clear_shapes()
  5251. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  5252. self.shell.init_tcl()
  5253. # delete any selection shape on canvas
  5254. self.delete_selection_shape()
  5255. # delete all FlatCAM objects
  5256. self.collection.delete_all()
  5257. # add in Selected tab an initial text that describe the flow of work in FlatCAm
  5258. self.setup_component_editor()
  5259. # Clear project filename
  5260. self.project_filename = None
  5261. # Load the application defaults
  5262. self.defaults.load(filename=os.path.join(self.data_path, 'current_defaults.FlatConfig'))
  5263. # Re-fresh project options
  5264. self.on_options_app2project()
  5265. # Init FlatCAMTools
  5266. self.init_tools()
  5267. # Try to close all tabs in the PlotArea but only if the AppGUI is active (CLI is None)
  5268. if cli is None:
  5269. # we need to go in reverse because once we remove a tab then the index changes
  5270. # meaning that removing the first tab (idx = 0) then the tab at former idx = 1 will assume idx = 0
  5271. # and so on. Therefore the deletion should be done in reverse
  5272. wdg_count = self.ui.plot_tab_area.tabBar.count() - 1
  5273. for index in range(wdg_count, -1, -1):
  5274. try:
  5275. self.ui.plot_tab_area.closeTab(index)
  5276. except Exception as e:
  5277. log.debug("App.on_file_new() --> %s" % str(e))
  5278. # # And then add again the Plot Area
  5279. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  5280. self.ui.plot_tab_area.protectTab(0)
  5281. # take the focus of the Notebook on Project Tab.
  5282. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5283. self.set_ui_title(name=_("New Project - Not saved"))
  5284. def obj_properties(self):
  5285. """
  5286. Will launch the object Properties Tool
  5287. :return:
  5288. """
  5289. self.defaults.report_usage("obj_properties()")
  5290. self.properties_tool.run(toggle=False)
  5291. def on_project_context_save(self):
  5292. """
  5293. Wrapper, will save the object function of it's type
  5294. :return:
  5295. """
  5296. obj = self.collection.get_active()
  5297. if type(obj) == GeometryObject:
  5298. self.on_file_exportdxf()
  5299. elif type(obj) == ExcellonObject:
  5300. self.on_file_saveexcellon()
  5301. elif type(obj) == CNCJobObject:
  5302. obj.on_exportgcode_button_click()
  5303. elif type(obj) == GerberObject:
  5304. self.on_file_savegerber()
  5305. elif type(obj) == ScriptObject:
  5306. self.on_file_savescript()
  5307. elif type(obj) == DocumentObject:
  5308. self.on_file_savedocument()
  5309. def obj_move(self):
  5310. """
  5311. Callback for the Move menu entry in various Context Menu's.
  5312. :return:
  5313. """
  5314. self.defaults.report_usage("obj_move()")
  5315. self.move_tool.run(toggle=False)
  5316. def on_fileopengerber(self, signal, name=None):
  5317. """
  5318. File menu callback for opening a Gerber.
  5319. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5320. :param name:
  5321. :return: None
  5322. """
  5323. self.defaults.report_usage("on_fileopengerber")
  5324. App.log.debug("on_fileopengerber()")
  5325. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *" \
  5326. ".gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  5327. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd);;" \
  5328. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  5329. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  5330. "*.mil);;" \
  5331. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  5332. "Allegro Files (*.art);;" \
  5333. "Mentor Files (*.pho *.gdo);;" \
  5334. "All Files (*.*)"
  5335. if name is None:
  5336. try:
  5337. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  5338. directory=self.get_last_folder(),
  5339. filter=_filter_)
  5340. except TypeError:
  5341. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  5342. filenames = [str(filename) for filename in filenames]
  5343. else:
  5344. filenames = [name]
  5345. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5346. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5347. _("Opening Gerber file.")),
  5348. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5349. color=QtGui.QColor("gray"))
  5350. if len(filenames) == 0:
  5351. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5352. else:
  5353. for filename in filenames:
  5354. if filename != '':
  5355. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  5356. def on_fileopenexcellon(self, signal, name=None):
  5357. """
  5358. File menu callback for opening an Excellon file.
  5359. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5360. :param name:
  5361. :return: None
  5362. """
  5363. self.defaults.report_usage("on_fileopenexcellon")
  5364. App.log.debug("on_fileopenexcellon()")
  5365. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  5366. "All Files (*.*)"
  5367. if name is None:
  5368. try:
  5369. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  5370. directory=self.get_last_folder(),
  5371. filter=_filter_)
  5372. except TypeError:
  5373. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  5374. filenames = [str(filename) for filename in filenames]
  5375. else:
  5376. filenames = [str(name)]
  5377. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5378. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5379. _("Opening Excellon file.")),
  5380. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5381. color=QtGui.QColor("gray"))
  5382. if len(filenames) == 0:
  5383. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  5384. else:
  5385. for filename in filenames:
  5386. if filename != '':
  5387. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  5388. def on_fileopengcode(self, signal, name=None):
  5389. """
  5390. File menu call back for opening gcode.
  5391. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5392. :param name:
  5393. :return:
  5394. """
  5395. self.defaults.report_usage("on_fileopengcode")
  5396. App.log.debug("on_fileopengcode()")
  5397. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  5398. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  5399. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.sbp *.mpf);;" \
  5400. "All Files (*.*)"
  5401. if name is None:
  5402. try:
  5403. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  5404. directory=self.get_last_folder(),
  5405. filter=_filter_)
  5406. except TypeError:
  5407. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  5408. filenames = [str(filename) for filename in filenames]
  5409. else:
  5410. filenames = [name]
  5411. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5412. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5413. _("Opening G-Code file.")),
  5414. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5415. color=QtGui.QColor("gray"))
  5416. if len(filenames) == 0:
  5417. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5418. else:
  5419. for filename in filenames:
  5420. if filename != '':
  5421. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename, None, True]})
  5422. def on_file_openproject(self, signal):
  5423. """
  5424. File menu callback for opening a project.
  5425. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5426. :return: None
  5427. """
  5428. self.defaults.report_usage("on_file_openproject")
  5429. App.log.debug("on_file_openproject()")
  5430. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  5431. try:
  5432. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  5433. directory=self.get_last_folder(), filter=_filter_)
  5434. except TypeError:
  5435. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  5436. # The Qt methods above will return a QString which can cause problems later.
  5437. # So far json.dump() will fail to serialize it.
  5438. # TODO: Improve the serialization methods and remove this fix.
  5439. filename = str(filename)
  5440. if filename == "":
  5441. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5442. else:
  5443. # self.worker_task.emit({'fcn': self.open_project,
  5444. # 'params': [filename]})
  5445. # The above was failing because open_project() is not
  5446. # thread safe. The new_project()
  5447. self.open_project(filename)
  5448. def on_fileopenhpgl2(self, signal, name=None):
  5449. """
  5450. File menu callback for opening a HPGL2.
  5451. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5452. :param name:
  5453. :return: None
  5454. """
  5455. self.defaults.report_usage("on_fileopenhpgl2")
  5456. App.log.debug("on_fileopenhpgl2()")
  5457. _filter_ = "HPGL2 Files (*.plt);;" \
  5458. "All Files (*.*)"
  5459. if name is None:
  5460. try:
  5461. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"),
  5462. directory=self.get_last_folder(),
  5463. filter=_filter_)
  5464. except TypeError:
  5465. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"), filter=_filter_)
  5466. filenames = [str(filename) for filename in filenames]
  5467. else:
  5468. filenames = [name]
  5469. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5470. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5471. _("Opening HPGL2 file.")),
  5472. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5473. color=QtGui.QColor("gray"))
  5474. if len(filenames) == 0:
  5475. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5476. else:
  5477. for filename in filenames:
  5478. if filename != '':
  5479. self.worker_task.emit({'fcn': self.open_hpgl2, 'params': [filename]})
  5480. def on_file_openconfig(self, signal):
  5481. """
  5482. File menu callback for opening a config file.
  5483. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5484. :return: None
  5485. """
  5486. self.defaults.report_usage("on_file_openconfig")
  5487. App.log.debug("on_file_openconfig()")
  5488. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  5489. try:
  5490. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  5491. directory=self.data_path, filter=_filter_)
  5492. except TypeError:
  5493. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  5494. filter=_filter_)
  5495. if filename == "":
  5496. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5497. else:
  5498. self.open_config_file(filename)
  5499. def on_file_exportsvg(self):
  5500. """
  5501. Callback for menu item File->Export SVG.
  5502. :return: None
  5503. """
  5504. self.defaults.report_usage("on_file_exportsvg")
  5505. App.log.debug("on_file_exportsvg()")
  5506. obj = self.collection.get_active()
  5507. if obj is None:
  5508. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5509. msg = _("Please Select a Geometry object to export")
  5510. msgbox = QtWidgets.QMessageBox()
  5511. msgbox.setInformativeText(msg)
  5512. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5513. msgbox.setDefaultButton(bt_ok)
  5514. msgbox.exec_()
  5515. return
  5516. # Check for more compatible types and add as required
  5517. if (not isinstance(obj, GeometryObject)
  5518. and not isinstance(obj, GerberObject)
  5519. and not isinstance(obj, CNCJobObject)
  5520. and not isinstance(obj, ExcellonObject)):
  5521. msg = '[ERROR_NOTCL] %s' % \
  5522. _("Only Geometry, Gerber and CNCJob objects can be used.")
  5523. msgbox = QtWidgets.QMessageBox()
  5524. msgbox.setInformativeText(msg)
  5525. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5526. msgbox.setDefaultButton(bt_ok)
  5527. msgbox.exec_()
  5528. return
  5529. name = obj.options["name"]
  5530. _filter = "SVG File (*.svg);;All Files (*.*)"
  5531. try:
  5532. filename, _f = FCFileSaveDialog.get_saved_filename(
  5533. caption=_("Export SVG"),
  5534. directory=self.get_last_save_folder() + '/' + str(name) + '_svg',
  5535. filter=_filter)
  5536. except TypeError:
  5537. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export SVG"), filter=_filter)
  5538. filename = str(filename)
  5539. if filename == "":
  5540. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  5541. return
  5542. else:
  5543. self.export_svg(name, filename)
  5544. if self.defaults["global_open_style"] is False:
  5545. self.file_opened.emit("SVG", filename)
  5546. self.file_saved.emit("SVG", filename)
  5547. def on_file_exportpng(self):
  5548. self.defaults.report_usage("on_file_exportpng")
  5549. App.log.debug("on_file_exportpng()")
  5550. self.date = str(datetime.today()).rpartition('.')[0]
  5551. self.date = ''.join(c for c in self.date if c not in ':-')
  5552. self.date = self.date.replace(' ', '_')
  5553. if self.is_legacy is False:
  5554. image = _screenshot()
  5555. data = np.asarray(image)
  5556. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  5557. self.inform.emit('[[WARNING_NOTCL]] %s' % _('Data must be a 3D array with last dimension 3 or 4'))
  5558. return
  5559. filter_ = "PNG File (*.png);;All Files (*.*)"
  5560. try:
  5561. filename, _f = FCFileSaveDialog.get_saved_filename(
  5562. caption=_("Export PNG Image"),
  5563. directory=self.get_last_save_folder() + '/png_' + self.date,
  5564. filter=filter_)
  5565. except TypeError:
  5566. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export PNG Image"), filter=filter_)
  5567. filename = str(filename)
  5568. if filename == "":
  5569. self.inform.emit(_("Cancelled."))
  5570. return
  5571. else:
  5572. if self.is_legacy is False:
  5573. write_png(filename, data)
  5574. else:
  5575. self.plotcanvas.figure.savefig(filename)
  5576. if self.defaults["global_open_style"] is False:
  5577. self.file_opened.emit("png", filename)
  5578. self.file_saved.emit("png", filename)
  5579. def on_file_savegerber(self):
  5580. """
  5581. Callback for menu item in Project context menu.
  5582. :return: None
  5583. """
  5584. self.defaults.report_usage("on_file_savegerber")
  5585. App.log.debug("on_file_savegerber()")
  5586. obj = self.collection.get_active()
  5587. if obj is None:
  5588. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5589. return
  5590. # Check for more compatible types and add as required
  5591. if not isinstance(obj, GerberObject):
  5592. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  5593. return
  5594. name = self.collection.get_active().options["name"]
  5595. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  5596. try:
  5597. filename, _f = FCFileSaveDialog.get_saved_filename(
  5598. caption="Save Gerber source file",
  5599. directory=self.get_last_save_folder() + '/' + name,
  5600. filter=_filter)
  5601. except TypeError:
  5602. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Gerber source file"), filter=_filter)
  5603. filename = str(filename)
  5604. if filename == "":
  5605. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5606. return
  5607. else:
  5608. self.save_source_file(name, filename)
  5609. if self.defaults["global_open_style"] is False:
  5610. self.file_opened.emit("Gerber", filename)
  5611. self.file_saved.emit("Gerber", filename)
  5612. def on_file_savescript(self):
  5613. """
  5614. Callback for menu item in Project context menu.
  5615. :return: None
  5616. """
  5617. self.defaults.report_usage("on_file_savescript")
  5618. App.log.debug("on_file_savescript()")
  5619. obj = self.collection.get_active()
  5620. if obj is None:
  5621. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5622. return
  5623. # Check for more compatible types and add as required
  5624. if not isinstance(obj, ScriptObject):
  5625. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Script objects can be saved as TCL Script files..."))
  5626. return
  5627. name = self.collection.get_active().options["name"]
  5628. _filter = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  5629. try:
  5630. filename, _f = FCFileSaveDialog.get_saved_filename(
  5631. caption="Save Script source file",
  5632. directory=self.get_last_save_folder() + '/' + name,
  5633. filter=_filter)
  5634. except TypeError:
  5635. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Script source file"), filter=_filter)
  5636. filename = str(filename)
  5637. if filename == "":
  5638. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5639. return
  5640. else:
  5641. self.save_source_file(name, filename)
  5642. if self.defaults["global_open_style"] is False:
  5643. self.file_opened.emit("Script", filename)
  5644. self.file_saved.emit("Script", filename)
  5645. def on_file_savedocument(self):
  5646. """
  5647. Callback for menu item in Project context menu.
  5648. :return: None
  5649. """
  5650. self.defaults.report_usage("on_file_savedocument")
  5651. App.log.debug("on_file_savedocument()")
  5652. obj = self.collection.get_active()
  5653. if obj is None:
  5654. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5655. return
  5656. # Check for more compatible types and add as required
  5657. if not isinstance(obj, ScriptObject):
  5658. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Document objects can be saved as Document files..."))
  5659. return
  5660. name = self.collection.get_active().options["name"]
  5661. _filter = "FlatCAM Documents (*.FlatDoc);;All Files (*.*)"
  5662. try:
  5663. filename, _f = FCFileSaveDialog.get_saved_filename(
  5664. caption="Save Document source file",
  5665. directory=self.get_last_save_folder() + '/' + name,
  5666. filter=_filter)
  5667. except TypeError:
  5668. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Document source file"), filter=_filter)
  5669. filename = str(filename)
  5670. if filename == "":
  5671. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5672. return
  5673. else:
  5674. self.save_source_file(name, filename)
  5675. if self.defaults["global_open_style"] is False:
  5676. self.file_opened.emit("Document", filename)
  5677. self.file_saved.emit("Document", filename)
  5678. def on_file_saveexcellon(self):
  5679. """
  5680. Callback for menu item in project context menu.
  5681. :return: None
  5682. """
  5683. self.defaults.report_usage("on_file_saveexcellon")
  5684. App.log.debug("on_file_saveexcellon()")
  5685. obj = self.collection.get_active()
  5686. if obj is None:
  5687. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5688. return
  5689. # Check for more compatible types and add as required
  5690. if not isinstance(obj, ExcellonObject):
  5691. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  5692. return
  5693. name = self.collection.get_active().options["name"]
  5694. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  5695. try:
  5696. filename, _f = FCFileSaveDialog.get_saved_filename(
  5697. caption=_("Save Excellon source file"),
  5698. directory=self.get_last_save_folder() + '/' + name,
  5699. filter=_filter)
  5700. except TypeError:
  5701. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Excellon source file"), filter=_filter)
  5702. filename = str(filename)
  5703. if filename == "":
  5704. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5705. return
  5706. else:
  5707. self.save_source_file(name, filename)
  5708. if self.defaults["global_open_style"] is False:
  5709. self.file_opened.emit("Excellon", filename)
  5710. self.file_saved.emit("Excellon", filename)
  5711. def on_file_exportexcellon(self):
  5712. """
  5713. Callback for menu item File->Export->Excellon.
  5714. :return: None
  5715. """
  5716. self.defaults.report_usage("on_file_exportexcellon")
  5717. App.log.debug("on_file_exportexcellon()")
  5718. obj = self.collection.get_active()
  5719. if obj is None:
  5720. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5721. return
  5722. # Check for more compatible types and add as required
  5723. if not isinstance(obj, ExcellonObject):
  5724. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  5725. return
  5726. name = self.collection.get_active().options["name"]
  5727. _filter = self.defaults["excellon_save_filters"]
  5728. try:
  5729. filename, _f = FCFileSaveDialog.get_saved_filename(
  5730. caption=_("Export Excellon"),
  5731. directory=self.get_last_save_folder() + '/' + name,
  5732. filter=_filter)
  5733. except TypeError:
  5734. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Excellon"), filter=_filter)
  5735. filename = str(filename)
  5736. if filename == "":
  5737. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5738. return
  5739. else:
  5740. used_extension = filename.rpartition('.')[2]
  5741. obj.update_filters(last_ext=used_extension, filter_string='excellon_save_filters')
  5742. self.export_excellon(name, filename)
  5743. if self.defaults["global_open_style"] is False:
  5744. self.file_opened.emit("Excellon", filename)
  5745. self.file_saved.emit("Excellon", filename)
  5746. def on_file_exportgerber(self):
  5747. """
  5748. Callback for menu item File->Export->Gerber.
  5749. :return: None
  5750. """
  5751. self.defaults.report_usage("on_file_exportgerber")
  5752. App.log.debug("on_file_exportgerber()")
  5753. obj = self.collection.get_active()
  5754. if obj is None:
  5755. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5756. return
  5757. # Check for more compatible types and add as required
  5758. if not isinstance(obj, GerberObject):
  5759. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  5760. return
  5761. name = self.collection.get_active().options["name"]
  5762. _filter_ = self.defaults['gerber_save_filters']
  5763. try:
  5764. filename, _f = FCFileSaveDialog.get_saved_filename(
  5765. caption=_("Export Gerber"),
  5766. directory=self.get_last_save_folder() + '/' + name,
  5767. filter=_filter_)
  5768. except TypeError:
  5769. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Gerber"), filter=_filter_)
  5770. filename = str(filename)
  5771. if filename == "":
  5772. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5773. return
  5774. else:
  5775. used_extension = filename.rpartition('.')[2]
  5776. obj.update_filters(last_ext=used_extension, filter_string='gerber_save_filters')
  5777. self.export_gerber(name, filename)
  5778. if self.defaults["global_open_style"] is False:
  5779. self.file_opened.emit("Gerber", filename)
  5780. self.file_saved.emit("Gerber", filename)
  5781. def on_file_exportdxf(self):
  5782. """
  5783. Callback for menu item File->Export DXF.
  5784. :return: None
  5785. """
  5786. self.defaults.report_usage("on_file_exportdxf")
  5787. App.log.debug("on_file_exportdxf()")
  5788. obj = self.collection.get_active()
  5789. if obj is None:
  5790. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5791. msg = _("Please Select a Geometry object to export")
  5792. msgbox = QtWidgets.QMessageBox()
  5793. msgbox.setInformativeText(msg)
  5794. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5795. msgbox.setDefaultButton(bt_ok)
  5796. msgbox.exec_()
  5797. return
  5798. # Check for more compatible types and add as required
  5799. if not isinstance(obj, GeometryObject):
  5800. msg = '[ERROR_NOTCL] %s' % _("Only Geometry objects can be used.")
  5801. msgbox = QtWidgets.QMessageBox()
  5802. msgbox.setInformativeText(msg)
  5803. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5804. msgbox.setDefaultButton(bt_ok)
  5805. msgbox.exec_()
  5806. return
  5807. name = self.collection.get_active().options["name"]
  5808. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  5809. try:
  5810. filename, _f = FCFileSaveDialog.get_saved_filename(
  5811. caption=_("Export DXF"),
  5812. directory=self.get_last_save_folder() + '/' + name,
  5813. filter=_filter_)
  5814. except TypeError:
  5815. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export DXF"), filter=_filter_)
  5816. filename = str(filename)
  5817. if filename == "":
  5818. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5819. return
  5820. else:
  5821. self.export_dxf(name, filename)
  5822. if self.defaults["global_open_style"] is False:
  5823. self.file_opened.emit("DXF", filename)
  5824. self.file_saved.emit("DXF", filename)
  5825. def on_file_importsvg(self, type_of_obj):
  5826. """
  5827. Callback for menu item File->Import SVG.
  5828. :param type_of_obj: to import the SVG as Geometry or as Gerber
  5829. :type type_of_obj: str
  5830. :return: None
  5831. """
  5832. self.defaults.report_usage("on_file_importsvg")
  5833. App.log.debug("on_file_importsvg()")
  5834. _filter_ = "SVG File .svg (*.svg);;All Files (*.*)"
  5835. try:
  5836. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  5837. directory=self.get_last_folder(), filter=_filter_)
  5838. except TypeError:
  5839. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  5840. filter=_filter_)
  5841. if type_of_obj != "geometry" and type_of_obj != "gerber":
  5842. type_of_obj = "geometry"
  5843. filenames = [str(filename) for filename in filenames]
  5844. if len(filenames) == 0:
  5845. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5846. else:
  5847. for filename in filenames:
  5848. if filename != '':
  5849. self.worker_task.emit({'fcn': self.import_svg,
  5850. 'params': [filename, type_of_obj]})
  5851. def on_file_importdxf(self, type_of_obj):
  5852. """
  5853. Callback for menu item File->Import DXF.
  5854. :param type_of_obj: to import the DXF as Geometry or as Gerber
  5855. :type type_of_obj: str
  5856. :return: None
  5857. """
  5858. self.defaults.report_usage("on_file_importdxf")
  5859. App.log.debug("on_file_importdxf()")
  5860. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  5861. try:
  5862. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  5863. directory=self.get_last_folder(),
  5864. filter=_filter_)
  5865. except TypeError:
  5866. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  5867. filter=_filter_)
  5868. if type_of_obj != "geometry" and type_of_obj != "gerber":
  5869. type_of_obj = "geometry"
  5870. filenames = [str(filename) for filename in filenames]
  5871. if len(filenames) == 0:
  5872. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5873. else:
  5874. for filename in filenames:
  5875. if filename != '':
  5876. self.worker_task.emit({'fcn': self.import_dxf,
  5877. 'params': [filename, type_of_obj]})
  5878. # ###############################################################################################################
  5879. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  5880. # ###############################################################################################################
  5881. def init_code_editor(self, name):
  5882. self.text_editor_tab = TextEditor(app=self, plain_text=True)
  5883. # add the tab if it was closed
  5884. self.ui.plot_tab_area.addTab(self.text_editor_tab, '%s' % name)
  5885. self.text_editor_tab.setObjectName('text_editor_tab')
  5886. # delete the absolute and relative position and messages in the infobar
  5887. self.ui.position_label.setText("")
  5888. # self.ui.rel_position_label.setText("")
  5889. # first clear previous text in text editor (if any)
  5890. self.text_editor_tab.code_editor.clear()
  5891. self.text_editor_tab.code_editor.setReadOnly(False)
  5892. self.toggle_codeeditor = True
  5893. self.text_editor_tab.code_editor.completer_enable = False
  5894. self.text_editor_tab.buttonRun.hide()
  5895. # make sure to keep a reference to the code editor
  5896. self.reference_code_editor = self.text_editor_tab.code_editor
  5897. # Switch plot_area to CNCJob tab
  5898. self.ui.plot_tab_area.setCurrentWidget(self.text_editor_tab)
  5899. def on_view_source(self):
  5900. """
  5901. Called when the user wants to see the source file of the selected object
  5902. :return:
  5903. """
  5904. self.inform.emit('%s' % _("Viewing the source code of the selected object."))
  5905. self.proc_container.view.set_busy(_("Loading..."))
  5906. try:
  5907. obj = self.collection.get_active()
  5908. except Exception as e:
  5909. log.debug("App.on_view_source() --> %s" % str(e))
  5910. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  5911. return 'fail'
  5912. if obj is None:
  5913. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  5914. return 'fail'
  5915. flt = "All Files (*.*)"
  5916. if obj.kind == 'gerber':
  5917. flt = "Gerber Files .gbr (*.GBR);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  5918. elif obj.kind == 'excellon':
  5919. flt = "Excellon Files .drl (*.DRL);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  5920. elif obj.kind == 'cncjob':
  5921. flt = "GCode Files .nc (*.NC);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  5922. self.source_editor_tab = TextEditor(app=self, plain_text=True)
  5923. # add the tab if it was closed
  5924. self.ui.plot_tab_area.addTab(self.source_editor_tab, '%s' % _("Source Editor"))
  5925. self.source_editor_tab.setObjectName('source_editor_tab')
  5926. # delete the absolute and relative position and messages in the infobar
  5927. self.ui.position_label.setText("")
  5928. # self.ui.rel_position_label.setText("")
  5929. # first clear previous text in text editor (if any)
  5930. self.source_editor_tab.code_editor.clear()
  5931. self.source_editor_tab.code_editor.setReadOnly(False)
  5932. self.source_editor_tab.code_editor.completer_enable = False
  5933. self.source_editor_tab.buttonRun.hide()
  5934. # Switch plot_area to CNCJob tab
  5935. self.ui.plot_tab_area.setCurrentWidget(self.source_editor_tab)
  5936. try:
  5937. self.source_editor_tab.buttonOpen.clicked.disconnect()
  5938. except TypeError:
  5939. pass
  5940. self.source_editor_tab.buttonOpen.clicked.connect(lambda: self.source_editor_tab.handleOpen(filt=flt))
  5941. try:
  5942. self.source_editor_tab.buttonSave.clicked.disconnect()
  5943. except TypeError:
  5944. pass
  5945. self.source_editor_tab.buttonSave.clicked.connect(lambda: self.source_editor_tab.handleSaveGCode(filt=flt))
  5946. # then append the text from GCode to the text editor
  5947. if obj.kind == 'cncjob':
  5948. try:
  5949. file = obj.export_gcode(
  5950. preamble=self.defaults["cncjob_prepend"],
  5951. postamble=self.defaults["cncjob_append"],
  5952. to_file=True)
  5953. if file == 'fail':
  5954. return 'fail'
  5955. except AttributeError:
  5956. self.inform.emit('[WARNING_NOTCL] %s' %
  5957. _("There is no selected object for which to see it's source file code."))
  5958. return 'fail'
  5959. else:
  5960. try:
  5961. file = StringIO(obj.source_file)
  5962. except (AttributeError, TypeError):
  5963. self.inform.emit('[WARNING_NOTCL] %s' %
  5964. _("There is no selected object for which to see it's source file code."))
  5965. return 'fail'
  5966. self.source_editor_tab.t_frame.hide()
  5967. try:
  5968. self.source_editor_tab.code_editor.setPlainText(file.getvalue())
  5969. # for line in file:
  5970. # QtWidgets.QApplication.processEvents()
  5971. # proc_line = str(line).strip('\n')
  5972. # self.source_editor_tab.code_editor.append(proc_line)
  5973. except Exception as e:
  5974. log.debug('App.on_view_source() -->%s' % str(e))
  5975. self.inform.emit('[ERROR] %s: %s' % (_('Failed to load the source code for the selected object'), str(e)))
  5976. return
  5977. self.source_editor_tab.handleTextChanged()
  5978. self.source_editor_tab.t_frame.show()
  5979. self.source_editor_tab.code_editor.moveCursor(QtGui.QTextCursor.Start)
  5980. self.proc_container.view.set_idle()
  5981. # self.ui.show()
  5982. def on_toggle_code_editor(self):
  5983. self.defaults.report_usage("on_toggle_code_editor()")
  5984. if self.toggle_codeeditor is False:
  5985. self.init_code_editor(name=_("Code Editor"))
  5986. self.text_editor_tab.buttonOpen.clicked.disconnect()
  5987. self.text_editor_tab.buttonOpen.clicked.connect(self.text_editor_tab.handleOpen)
  5988. self.text_editor_tab.buttonSave.clicked.disconnect()
  5989. self.text_editor_tab.buttonSave.clicked.connect(self.text_editor_tab.handleSaveGCode)
  5990. else:
  5991. for idx in range(self.ui.plot_tab_area.count()):
  5992. if self.ui.plot_tab_area.widget(idx).objectName() == "text_editor_tab":
  5993. self.ui.plot_tab_area.closeTab(idx)
  5994. break
  5995. self.toggle_codeeditor = False
  5996. def on_code_editor_close(self):
  5997. self.toggle_codeeditor = False
  5998. def goto_text_line(self):
  5999. """
  6000. Will scroll a text to the specified text line.
  6001. :return: None
  6002. """
  6003. dia_box = Dialog_box(title=_("Go to Line ..."),
  6004. label=_("Line:"),
  6005. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  6006. initial_text='')
  6007. try:
  6008. line = int(dia_box.location) - 1
  6009. except (ValueError, TypeError):
  6010. line = 0
  6011. if dia_box.ok:
  6012. # make sure to move first the cursor at the end so after finding the line the line will be positioned
  6013. # at the top of the window
  6014. self.ui.plot_tab_area.currentWidget().code_editor.moveCursor(QTextCursor.End)
  6015. # get the document() of the TextEditor
  6016. doc = self.ui.plot_tab_area.currentWidget().code_editor.document()
  6017. # create a Text Cursor based on the searched line
  6018. cursor = QTextCursor(doc.findBlockByLineNumber(line))
  6019. # set cursor of the code editor with the cursor at the searcehd line
  6020. self.ui.plot_tab_area.currentWidget().code_editor.setTextCursor(cursor)
  6021. def on_filenewscript(self, silent=False):
  6022. """
  6023. Will create a new script file and open it in the Code Editor
  6024. :param silent: if True will not display status messages
  6025. :return: None
  6026. """
  6027. if silent is False:
  6028. self.inform.emit('[success] %s' % _("New TCL script file created in Code Editor."))
  6029. # delete the absolute and relative position and messages in the infobar
  6030. self.ui.position_label.setText("")
  6031. # self.ui.rel_position_label.setText("")
  6032. self.app_obj.new_script_object()
  6033. # script_text = script_obj.source_file
  6034. #
  6035. # self.proc_container.view.set_busy(_("Loading..."))
  6036. # script_obj.script_editor_tab.t_frame.hide()
  6037. #
  6038. # script_obj.script_editor_tab.t_frame.show()
  6039. # self.proc_container.view.set_idle()
  6040. def on_fileopenscript(self, name=None, silent=False):
  6041. """
  6042. Will open a Tcl script file into the Code Editor
  6043. :param silent: if True will not display status messages
  6044. :param name: name of a Tcl script file to open
  6045. :return: None
  6046. """
  6047. self.defaults.report_usage("on_fileopenscript")
  6048. App.log.debug("on_fileopenscript()")
  6049. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6050. "All Files (*.*)"
  6051. if name:
  6052. filenames = [name]
  6053. else:
  6054. try:
  6055. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6056. caption=_("Open TCL script"), directory=self.get_last_folder(), filter=_filter_)
  6057. except TypeError:
  6058. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6059. if len(filenames) == 0:
  6060. if silent is False:
  6061. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6062. else:
  6063. for filename in filenames:
  6064. if filename != '':
  6065. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6066. def on_fileopenscript_example(self, name=None, silent=False):
  6067. """
  6068. Will open a Tcl script file into the Code Editor
  6069. :param silent: if True will not display status messages
  6070. :param name: name of a Tcl script file to open
  6071. :return:
  6072. """
  6073. self.defaults.report_usage("on_fileopenscript_example")
  6074. log.debug("on_fileopenscript_example()")
  6075. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6076. "All Files (*.*)"
  6077. # test if the app was frozen and choose the path for the configuration file
  6078. if getattr(sys, "frozen", False) is True:
  6079. example_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\assets\\examples'
  6080. else:
  6081. example_path = os.path.dirname(os.path.realpath(__file__)) + '\\assets\\examples'
  6082. if name:
  6083. filenames = [name]
  6084. else:
  6085. try:
  6086. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6087. caption=_("Open TCL script"), directory=example_path, filter=_filter_)
  6088. except TypeError:
  6089. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6090. if len(filenames) == 0:
  6091. if silent is False:
  6092. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6093. else:
  6094. for filename in filenames:
  6095. if filename != '':
  6096. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6097. def on_filerunscript(self, name=None, silent=False):
  6098. """
  6099. File menu callback for loading and running a TCL script.
  6100. :param silent: if True will not display status messages
  6101. :param name: name of a Tcl script file to be run by FlatCAM
  6102. :return: None
  6103. """
  6104. self.defaults.report_usage("on_filerunscript")
  6105. App.log.debug("on_file_runscript()")
  6106. if name:
  6107. filename = name
  6108. if self.cmd_line_headless != 1:
  6109. self.splash.showMessage('%s: %ssec\n%s' %
  6110. (_("Canvas initialization started.\n"
  6111. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6112. _("Executing ScriptObject file.")
  6113. ),
  6114. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6115. color=QtGui.QColor("gray"))
  6116. else:
  6117. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6118. "All Files (*.*)"
  6119. try:
  6120. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  6121. directory=self.get_last_folder(), filter=_filter_)
  6122. except TypeError:
  6123. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  6124. # The Qt methods above will return a QString which can cause problems later.
  6125. # So far json.dump() will fail to serialize it.
  6126. filename = str(filename)
  6127. if filename == "":
  6128. if silent is False:
  6129. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6130. else:
  6131. if self.cmd_line_headless != 1:
  6132. if self.ui.shell_dock.isHidden():
  6133. self.ui.shell_dock.show()
  6134. try:
  6135. with open(filename, "r") as tcl_script:
  6136. cmd_line_shellfile_content = tcl_script.read()
  6137. if self.cmd_line_headless != 1:
  6138. self.shell.exec_command(cmd_line_shellfile_content)
  6139. else:
  6140. self.shell.exec_command(cmd_line_shellfile_content, no_echo=True)
  6141. if silent is False:
  6142. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor and executed."))
  6143. except Exception as e:
  6144. log.debug("App.on_filerunscript() -> %s" % str(e))
  6145. sys.exit(2)
  6146. def on_file_saveproject(self, silent=False):
  6147. """
  6148. Callback for menu item File->Save Project. Saves the project to
  6149. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  6150. if set to None. The project is saved by calling ``self.save_project()``.
  6151. :param silent: if True will not display status messages
  6152. :return: None
  6153. """
  6154. self.defaults.report_usage("on_file_saveproject")
  6155. if self.project_filename is None:
  6156. self.on_file_saveprojectas()
  6157. else:
  6158. self.worker_task.emit({'fcn': self.save_project,
  6159. 'params': [self.project_filename, silent]})
  6160. if self.defaults["global_open_style"] is False:
  6161. self.file_opened.emit("project", self.project_filename)
  6162. self.file_saved.emit("project", self.project_filename)
  6163. self.set_ui_title(name=self.project_filename)
  6164. self.should_we_save = False
  6165. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  6166. """
  6167. Callback for menu item File->Save Project As... Opens a file
  6168. chooser and saves the project to the given file via
  6169. ``self.save_project()``.
  6170. :param make_copy if to be create a copy of the project; boolean
  6171. :param use_thread: if to be run in a separate thread; boolean
  6172. :param quit_action: if to be followed by quiting the application; boolean
  6173. :return: None
  6174. """
  6175. self.defaults.report_usage("on_file_saveprojectas")
  6176. self.date = str(datetime.today()).rpartition('.')[0]
  6177. self.date = ''.join(c for c in self.date if c not in ':-')
  6178. self.date = self.date.replace(' ', '_')
  6179. filter_ = "FlatCAM Project .FlatPrj (*.FlatPrj);; All Files (*.*)"
  6180. try:
  6181. filename, _f = FCFileSaveDialog.get_saved_filename(
  6182. caption=_("Save Project As ..."),
  6183. directory='{l_save}/{proj}_{date}'.format(l_save=str(self.get_last_save_folder()), date=self.date,
  6184. proj=_("Project")),
  6185. filter=filter_
  6186. )
  6187. except TypeError:
  6188. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Project As ..."), filter=filter_)
  6189. filename = str(filename)
  6190. if filename == '':
  6191. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6192. return
  6193. if use_thread is True:
  6194. self.worker_task.emit({'fcn': self.save_project,
  6195. 'params': [filename, quit_action]})
  6196. else:
  6197. self.save_project(filename, quit_action)
  6198. # self.save_project(filename)
  6199. if self.defaults["global_open_style"] is False:
  6200. self.file_opened.emit("project", filename)
  6201. self.file_saved.emit("project", filename)
  6202. if not make_copy:
  6203. self.project_filename = filename
  6204. self.set_ui_title(name=self.project_filename)
  6205. self.should_we_save = False
  6206. def on_file_save_objects_pdf(self, use_thread=True):
  6207. self.date = str(datetime.today()).rpartition('.')[0]
  6208. self.date = ''.join(c for c in self.date if c not in ':-')
  6209. self.date = self.date.replace(' ', '_')
  6210. try:
  6211. obj_selection = self.collection.get_selected()
  6212. if len(obj_selection) == 1:
  6213. obj_name = str(obj_selection[0].options['name'])
  6214. else:
  6215. obj_name = _("FlatCAM objects print")
  6216. except AttributeError as err:
  6217. log.debug("App.on_file_save_object_pdf() --> %s" % str(err))
  6218. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  6219. return
  6220. if not obj_selection:
  6221. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  6222. return
  6223. filter_ = "PDF File .pdf (*.PDF);; All Files (*.*)"
  6224. try:
  6225. filename, _f = FCFileSaveDialog.get_saved_filename(
  6226. caption=_("Save Object as PDF ..."),
  6227. directory='{l_save}/{obj_name}_{date}'.format(l_save=str(self.get_last_save_folder()),
  6228. obj_name=obj_name,
  6229. date=self.date),
  6230. filter=filter_
  6231. )
  6232. except TypeError:
  6233. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Object as PDF ..."), filter=filter_)
  6234. filename = str(filename)
  6235. if filename == '':
  6236. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6237. return
  6238. if use_thread is True:
  6239. self.proc_container.new(_("Printing PDF ... Please wait."))
  6240. self.worker_task.emit({'fcn': self.save_pdf, 'params': [filename, obj_selection]})
  6241. else:
  6242. self.save_pdf(filename, obj_selection)
  6243. # self.save_project(filename)
  6244. if self.defaults["global_open_style"] is False:
  6245. self.file_opened.emit("pdf", filename)
  6246. self.file_saved.emit("pdf", filename)
  6247. def save_pdf(self, file_name, obj_selection):
  6248. p_size = self.defaults['global_workspaceT']
  6249. orientation = self.defaults['global_workspace_orientation']
  6250. color = 'black'
  6251. transparency_level = 1.0
  6252. self.pagesize = {}
  6253. self.pagesize.update(
  6254. {
  6255. 'Bounds': None,
  6256. 'A0': (841 * mm, 1189 * mm),
  6257. 'A1': (594 * mm, 841 * mm),
  6258. 'A2': (420 * mm, 594 * mm),
  6259. 'A3': (297 * mm, 420 * mm),
  6260. 'A4': (210 * mm, 297 * mm),
  6261. 'A5': (148 * mm, 210 * mm),
  6262. 'A6': (105 * mm, 148 * mm),
  6263. 'A7': (74 * mm, 105 * mm),
  6264. 'A8': (52 * mm, 74 * mm),
  6265. 'A9': (37 * mm, 52 * mm),
  6266. 'A10': (26 * mm, 37 * mm),
  6267. 'B0': (1000 * mm, 1414 * mm),
  6268. 'B1': (707 * mm, 1000 * mm),
  6269. 'B2': (500 * mm, 707 * mm),
  6270. 'B3': (353 * mm, 500 * mm),
  6271. 'B4': (250 * mm, 353 * mm),
  6272. 'B5': (176 * mm, 250 * mm),
  6273. 'B6': (125 * mm, 176 * mm),
  6274. 'B7': (88 * mm, 125 * mm),
  6275. 'B8': (62 * mm, 88 * mm),
  6276. 'B9': (44 * mm, 62 * mm),
  6277. 'B10': (31 * mm, 44 * mm),
  6278. 'C0': (917 * mm, 1297 * mm),
  6279. 'C1': (648 * mm, 917 * mm),
  6280. 'C2': (458 * mm, 648 * mm),
  6281. 'C3': (324 * mm, 458 * mm),
  6282. 'C4': (229 * mm, 324 * mm),
  6283. 'C5': (162 * mm, 229 * mm),
  6284. 'C6': (114 * mm, 162 * mm),
  6285. 'C7': (81 * mm, 114 * mm),
  6286. 'C8': (57 * mm, 81 * mm),
  6287. 'C9': (40 * mm, 57 * mm),
  6288. 'C10': (28 * mm, 40 * mm),
  6289. # American paper sizes
  6290. 'LETTER': (8.5 * inch, 11 * inch),
  6291. 'LEGAL': (8.5 * inch, 14 * inch),
  6292. 'ELEVENSEVENTEEN': (11 * inch, 17 * inch),
  6293. # From https://en.wikipedia.org/wiki/Paper_size
  6294. 'JUNIOR_LEGAL': (5 * inch, 8 * inch),
  6295. 'HALF_LETTER': (5.5 * inch, 8 * inch),
  6296. 'GOV_LETTER': (8 * inch, 10.5 * inch),
  6297. 'GOV_LEGAL': (8.5 * inch, 13 * inch),
  6298. 'LEDGER': (17 * inch, 11 * inch),
  6299. }
  6300. )
  6301. exported_svg = []
  6302. for obj in obj_selection:
  6303. svg_obj = obj.export_svg(scale_stroke_factor=0.0,
  6304. scale_factor_x=None, scale_factor_y=None,
  6305. skew_factor_x=None, skew_factor_y=None,
  6306. mirror=None)
  6307. if obj.kind.lower() == 'gerber':
  6308. # color = self.defaults["gerber_plot_fill"][:-2]
  6309. color = obj.fill_color[:-2]
  6310. elif obj.kind.lower() == 'excellon':
  6311. color = '#C40000'
  6312. elif obj.kind.lower() == 'geometry':
  6313. color = self.defaults["global_draw_color"]
  6314. # Change the attributes of the exported SVG
  6315. # We don't need stroke-width
  6316. # We set opacity to maximum
  6317. # We set the colour to WHITE
  6318. root = ET.fromstring(svg_obj)
  6319. for child in root:
  6320. child.set('fill', str(color))
  6321. child.set('opacity', str(transparency_level))
  6322. child.set('stroke', str(color))
  6323. exported_svg.append(ET.tostring(root))
  6324. xmin = Inf
  6325. ymin = Inf
  6326. xmax = -Inf
  6327. ymax = -Inf
  6328. for obj in obj_selection:
  6329. try:
  6330. gxmin, gymin, gxmax, gymax = obj.bounds()
  6331. xmin = min([xmin, gxmin])
  6332. ymin = min([ymin, gymin])
  6333. xmax = max([xmax, gxmax])
  6334. ymax = max([ymax, gymax])
  6335. except Exception as e:
  6336. log.warning("DEV WARNING: Tried to get bounds of empty geometry in App.save_pdf(). %s" % str(e))
  6337. # Determine bounding area for svg export
  6338. bounds = [xmin, ymin, xmax, ymax]
  6339. size = bounds[2] - bounds[0], bounds[3] - bounds[1]
  6340. # This contain the measure units
  6341. uom = obj_selection[0].units.lower()
  6342. # Define a boundary around SVG of about 1.0mm (~39mils)
  6343. if uom in "mm":
  6344. boundary = 1.0
  6345. else:
  6346. boundary = 0.0393701
  6347. # Convert everything to strings for use in the xml doc
  6348. svgwidth = str(size[0] + (2 * boundary))
  6349. svgheight = str(size[1] + (2 * boundary))
  6350. minx = str(bounds[0] - boundary)
  6351. miny = str(bounds[1] + boundary + size[1])
  6352. # Add a SVG Header and footer to the svg output from shapely
  6353. # The transform flips the Y Axis so that everything renders
  6354. # properly within svg apps such as inkscape
  6355. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  6356. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  6357. svg_header += 'width="' + svgwidth + uom + '" '
  6358. svg_header += 'height="' + svgheight + uom + '" '
  6359. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  6360. svg_header += '>'
  6361. svg_header += '<g transform="scale(1,-1)">'
  6362. svg_footer = '</g> </svg>'
  6363. svg_elem = str(svg_header)
  6364. for svg_item in exported_svg:
  6365. svg_elem += str(svg_item)
  6366. svg_elem += str(svg_footer)
  6367. # Parse the xml through a xml parser just to add line feeds
  6368. # and to make it look more pretty for the output
  6369. doc = parse_xml_string(svg_elem)
  6370. doc_final = doc.toprettyxml()
  6371. try:
  6372. if self.defaults['units'].upper() == 'IN':
  6373. unit = inch
  6374. else:
  6375. unit = mm
  6376. doc_final = StringIO(doc_final)
  6377. drawing = svg2rlg(doc_final)
  6378. if p_size == 'Bounds':
  6379. renderPDF.drawToFile(drawing, file_name)
  6380. else:
  6381. if orientation == 'p':
  6382. page_size = portrait(self.pagesize[p_size])
  6383. else:
  6384. page_size = landscape(self.pagesize[p_size])
  6385. my_canvas = canvas.Canvas(file_name, pagesize=page_size)
  6386. my_canvas.translate(bounds[0] * unit, bounds[1] * unit)
  6387. renderPDF.draw(drawing, my_canvas, 0, 0)
  6388. my_canvas.save()
  6389. except Exception as e:
  6390. log.debug("App.save_pdf() --> PDF output --> %s" % str(e))
  6391. return 'fail'
  6392. self.inform.emit('[success] %s: %s' % (_("PDF file saved to"), file_name))
  6393. def export_svg(self, obj_name, filename, scale_stroke_factor=0.00):
  6394. """
  6395. Exports a Geometry Object to an SVG file.
  6396. :param obj_name: the name of the FlatCAM object to be saved as SVG
  6397. :param filename: Path to the SVG file to save to.
  6398. :param scale_stroke_factor: factor by which to change/scale the thickness of the features
  6399. :return:
  6400. """
  6401. self.defaults.report_usage("export_svg()")
  6402. if filename is None:
  6403. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6404. is not None else self.defaults["global_last_folder"]
  6405. self.log.debug("export_svg()")
  6406. try:
  6407. obj = self.collection.get_by_name(str(obj_name))
  6408. except Exception:
  6409. # TODO: The return behavior has not been established... should raise exception?
  6410. return "Could not retrieve object: %s" % obj_name
  6411. with self.proc_container.new(_("Exporting SVG")) as proc:
  6412. exported_svg = obj.export_svg(scale_stroke_factor=scale_stroke_factor)
  6413. # Determine bounding area for svg export
  6414. bounds = obj.bounds()
  6415. size = obj.size()
  6416. # Convert everything to strings for use in the xml doc
  6417. svgwidth = str(size[0])
  6418. svgheight = str(size[1])
  6419. minx = str(bounds[0])
  6420. miny = str(bounds[1] - size[1])
  6421. uom = obj.units.lower()
  6422. # Add a SVG Header and footer to the svg output from shapely
  6423. # The transform flips the Y Axis so that everything renders
  6424. # properly within svg apps such as inkscape
  6425. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  6426. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  6427. svg_header += 'width="' + svgwidth + uom + '" '
  6428. svg_header += 'height="' + svgheight + uom + '" '
  6429. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  6430. svg_header += '<g transform="scale(1,-1)">'
  6431. svg_footer = '</g> </svg>'
  6432. svg_elem = svg_header + exported_svg + svg_footer
  6433. # Parse the xml through a xml parser just to add line feeds
  6434. # and to make it look more pretty for the output
  6435. svgcode = parse_xml_string(svg_elem)
  6436. svgcode = svgcode.toprettyxml()
  6437. try:
  6438. with open(filename, 'w') as fp:
  6439. fp.write(svgcode)
  6440. except PermissionError:
  6441. self.inform.emit('[WARNING] %s' %
  6442. _("Permission denied, saving not possible.\n"
  6443. "Most likely another app is holding the file open and not accessible."))
  6444. return 'fail'
  6445. if self.defaults["global_open_style"] is False:
  6446. self.file_opened.emit("SVG", filename)
  6447. self.file_saved.emit("SVG", filename)
  6448. self.inform.emit('[success] %s: %s' % (_("SVG file exported to"), filename))
  6449. def save_source_file(self, obj_name, filename, use_thread=True):
  6450. """
  6451. Exports a FlatCAM Object to an Gerber/Excellon file.
  6452. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  6453. :param filename: Path to the Gerber file to save to.
  6454. :param use_thread: if to be run in a separate thread
  6455. :return:
  6456. """
  6457. self.defaults.report_usage("save source file()")
  6458. if filename is None:
  6459. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6460. is not None else self.defaults["global_last_folder"]
  6461. self.log.debug("save source file()")
  6462. obj = self.collection.get_by_name(obj_name)
  6463. file_string = StringIO(obj.source_file)
  6464. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  6465. if file_string.getvalue() == '':
  6466. self.inform.emit('[ERROR_NOTCL] %s' %
  6467. _("Save cancelled because source file is empty. Try to export the Gerber file."))
  6468. return 'fail'
  6469. try:
  6470. with open(filename, 'w') as file:
  6471. file.writelines('G04*\n')
  6472. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  6473. (obj.kind.upper(), str(self.version), str(self.version_date)))
  6474. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  6475. file.writelines('G04 Created on : %s*\n' % time_string)
  6476. for line in file_string:
  6477. file.writelines(line)
  6478. except PermissionError:
  6479. self.inform.emit('[WARNING] %s' %
  6480. _("Permission denied, saving not possible.\n"
  6481. "Most likely another app is holding the file open and not accessible."))
  6482. return 'fail'
  6483. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  6484. """
  6485. Exports a Excellon Object to an Excellon file.
  6486. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  6487. :param filename: Path to the Excellon file to save to.
  6488. :param local_use:
  6489. :param use_thread: if to be run in a separate thread
  6490. :return:
  6491. """
  6492. self.defaults.report_usage("export_excellon()")
  6493. if filename is None:
  6494. if self.defaults["global_last_save_folder"]:
  6495. filename = self.defaults["global_last_save_folder"] + '/' + 'exported_excellon'
  6496. else:
  6497. filename = self.defaults["global_last_folder"] + '/' + 'exported_excellon'
  6498. self.log.debug("export_excellon()")
  6499. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  6500. self.defaults["excellon_exp_decimals"]
  6501. )
  6502. if local_use is None:
  6503. try:
  6504. obj = self.collection.get_by_name(str(obj_name))
  6505. except Exception:
  6506. return "Could not retrieve object: %s" % obj_name
  6507. else:
  6508. obj = local_use
  6509. if not isinstance(obj, ExcellonObject):
  6510. self.inform.emit('[ERROR_NOTCL] %s' %
  6511. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6512. return
  6513. # updated units
  6514. eunits = self.defaults["excellon_exp_units"]
  6515. ewhole = self.defaults["excellon_exp_integer"]
  6516. efract = self.defaults["excellon_exp_decimals"]
  6517. ezeros = self.defaults["excellon_exp_zeros"]
  6518. eformat = self.defaults["excellon_exp_format"]
  6519. slot_type = self.defaults["excellon_exp_slot_type"]
  6520. fc_units = self.defaults['units'].upper()
  6521. if fc_units == 'MM':
  6522. factor = 1 if eunits == 'METRIC' else 0.03937
  6523. else:
  6524. factor = 25.4 if eunits == 'METRIC' else 1
  6525. def make_excellon():
  6526. try:
  6527. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  6528. header = 'M48\n'
  6529. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  6530. (str(self.version), str(self.version_date))
  6531. header += ';Filename: %s' % str(obj_name) + '\n'
  6532. header += ';Created on : %s' % time_str + '\n'
  6533. if eformat == 'dec':
  6534. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  6535. header += eunits + '\n'
  6536. for tool in obj.tools:
  6537. if eunits == 'METRIC':
  6538. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6539. tool=str(tool),
  6540. dec=2)
  6541. else:
  6542. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6543. tool=str(tool),
  6544. dec=4)
  6545. else:
  6546. if ezeros == 'LZ':
  6547. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  6548. form='ndec', e_zeros='LZ', factor=factor,
  6549. slot_type=slot_type)
  6550. header += '%s,%s\n' % (eunits, 'LZ')
  6551. header += format_exc
  6552. for tool in obj.tools:
  6553. if eunits == 'METRIC':
  6554. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6555. tool=str(tool),
  6556. dec=2)
  6557. else:
  6558. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6559. tool=str(tool),
  6560. dec=4)
  6561. else:
  6562. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  6563. form='ndec', e_zeros='TZ', factor=factor,
  6564. slot_type=slot_type)
  6565. header += '%s,%s\n' % (eunits, 'TZ')
  6566. header += format_exc
  6567. for tool in obj.tools:
  6568. if eunits == 'METRIC':
  6569. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6570. tool=str(tool),
  6571. dec=2)
  6572. else:
  6573. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6574. tool=str(tool),
  6575. dec=4)
  6576. header += '%\n'
  6577. footer = 'M30\n'
  6578. exported_excellon = header
  6579. exported_excellon += excellon_code
  6580. exported_excellon += footer
  6581. if local_use is None:
  6582. try:
  6583. with open(filename, 'w') as fp:
  6584. fp.write(exported_excellon)
  6585. except PermissionError:
  6586. self.inform.emit('[WARNING] %s' %
  6587. _("Permission denied, saving not possible.\n"
  6588. "Most likely another app is holding the file open and not accessible."))
  6589. return 'fail'
  6590. if self.defaults["global_open_style"] is False:
  6591. self.file_opened.emit("Excellon", filename)
  6592. self.file_saved.emit("Excellon", filename)
  6593. self.inform.emit('[success] %s: %s' % (_("Excellon file exported to"), filename))
  6594. else:
  6595. return exported_excellon
  6596. except Exception as e:
  6597. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  6598. return 'fail'
  6599. if use_thread is True:
  6600. with self.proc_container.new(_("Exporting Excellon")) as proc:
  6601. def job_thread_exc(app_obj):
  6602. ret = make_excellon()
  6603. if ret == 'fail':
  6604. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  6605. return
  6606. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  6607. else:
  6608. eret = make_excellon()
  6609. if eret == 'fail':
  6610. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  6611. return 'fail'
  6612. if local_use is not None:
  6613. return eret
  6614. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  6615. """
  6616. Exports a Gerber Object to an Gerber file.
  6617. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  6618. :param filename: Path to the Gerber file to save to.
  6619. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  6620. When not None, the value will be the actual Gerber object for which to create the Gerber code
  6621. :param use_thread: if to be run in a separate thread
  6622. :return:
  6623. """
  6624. self.defaults.report_usage("export_gerber()")
  6625. if filename is None:
  6626. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6627. is not None else self.defaults["global_last_folder"]
  6628. self.log.debug("export_gerber()")
  6629. if local_use is None:
  6630. try:
  6631. obj = self.collection.get_by_name(str(obj_name))
  6632. except Exception:
  6633. return "Could not retrieve object: %s" % obj_name
  6634. else:
  6635. obj = local_use
  6636. # updated units
  6637. gunits = self.defaults["gerber_exp_units"]
  6638. gwhole = self.defaults["gerber_exp_integer"]
  6639. gfract = self.defaults["gerber_exp_decimals"]
  6640. gzeros = self.defaults["gerber_exp_zeros"]
  6641. fc_units = self.defaults['units'].upper()
  6642. if fc_units == 'MM':
  6643. factor = 1 if gunits == 'MM' else 0.03937
  6644. else:
  6645. factor = 25.4 if gunits == 'MM' else 1
  6646. def make_gerber():
  6647. try:
  6648. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  6649. header = 'G04*\n'
  6650. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  6651. (str(self.version), str(self.version_date))
  6652. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  6653. header += 'G04 Created on : %s*' % time_str + '\n'
  6654. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  6655. header += "%MO{units}*%\n".format(units=gunits)
  6656. for apid in obj.apertures:
  6657. if obj.apertures[apid]['type'] == 'C':
  6658. header += "%ADD{apid}{type},{size}*%\n".format(
  6659. apid=str(apid),
  6660. type='C',
  6661. size=(factor * obj.apertures[apid]['size'])
  6662. )
  6663. elif obj.apertures[apid]['type'] == 'R':
  6664. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  6665. apid=str(apid),
  6666. type='R',
  6667. width=(factor * obj.apertures[apid]['width']),
  6668. height=(factor * obj.apertures[apid]['height'])
  6669. )
  6670. elif obj.apertures[apid]['type'] == 'O':
  6671. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  6672. apid=str(apid),
  6673. type='O',
  6674. width=(factor * obj.apertures[apid]['width']),
  6675. height=(factor * obj.apertures[apid]['height'])
  6676. )
  6677. header += '\n'
  6678. # obsolete units but some software may need it
  6679. if gunits == 'IN':
  6680. header += 'G70*\n'
  6681. else:
  6682. header += 'G71*\n'
  6683. # Absolute Mode
  6684. header += 'G90*\n'
  6685. header += 'G01*\n'
  6686. # positive polarity
  6687. header += '%LPD*%\n'
  6688. footer = 'M02*\n'
  6689. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  6690. exported_gerber = header
  6691. exported_gerber += gerber_code
  6692. exported_gerber += footer
  6693. if local_use is None:
  6694. try:
  6695. with open(filename, 'w') as fp:
  6696. fp.write(exported_gerber)
  6697. except PermissionError:
  6698. self.inform.emit('[WARNING] %s' %
  6699. _("Permission denied, saving not possible.\n"
  6700. "Most likely another app is holding the file open and not accessible."))
  6701. return 'fail'
  6702. if self.defaults["global_open_style"] is False:
  6703. self.file_opened.emit("Gerber", filename)
  6704. self.file_saved.emit("Gerber", filename)
  6705. self.inform.emit('[success] %s: %s' % (_("Gerber file exported to"), filename))
  6706. else:
  6707. return exported_gerber
  6708. except Exception as e:
  6709. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  6710. return 'fail'
  6711. if use_thread is True:
  6712. with self.proc_container.new(_("Exporting Gerber")) as proc:
  6713. def job_thread_grb(app_obj):
  6714. ret = make_gerber()
  6715. if ret == 'fail':
  6716. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  6717. return
  6718. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  6719. else:
  6720. gret = make_gerber()
  6721. if gret == 'fail':
  6722. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  6723. return 'fail'
  6724. if local_use is not None:
  6725. return gret
  6726. def export_dxf(self, obj_name, filename, use_thread=True):
  6727. """
  6728. Exports a Geometry Object to an DXF file.
  6729. :param obj_name: the name of the FlatCAM object to be saved as DXF
  6730. :param filename: Path to the DXF file to save to.
  6731. :param use_thread: if to be run in a separate thread
  6732. :return:
  6733. """
  6734. self.defaults.report_usage("export_dxf()")
  6735. if filename is None:
  6736. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6737. is not None else self.defaults["global_last_folder"]
  6738. self.log.debug("export_dxf()")
  6739. try:
  6740. obj = self.collection.get_by_name(str(obj_name))
  6741. except Exception:
  6742. # TODO: The return behavior has not been established... should raise exception?
  6743. return "Could not retrieve object: %s" % obj_name
  6744. def make_dxf():
  6745. try:
  6746. dxf_code = obj.export_dxf()
  6747. dxf_code.saveas(filename)
  6748. if self.defaults["global_open_style"] is False:
  6749. self.file_opened.emit("DXF", filename)
  6750. self.file_saved.emit("DXF", filename)
  6751. self.inform.emit('[success] %s: %s' % (_("DXF file exported to"), filename))
  6752. except Exception:
  6753. return 'fail'
  6754. if use_thread is True:
  6755. with self.proc_container.new(_("Exporting DXF")) as proc:
  6756. def job_thread_exc(app_obj):
  6757. ret_dxf_val = make_dxf()
  6758. if ret_dxf_val == 'fail':
  6759. app_obj.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  6760. return
  6761. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  6762. else:
  6763. ret = make_dxf()
  6764. if ret == 'fail':
  6765. self.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  6766. return
  6767. def import_svg(self, filename, geo_type='geometry', outname=None, plot=True):
  6768. """
  6769. Adds a new Geometry Object to the projects and populates
  6770. it with shapes extracted from the SVG file.
  6771. :param plot: If True then the resulting object will be plotted on canvas
  6772. :param filename: Path to the SVG file.
  6773. :param geo_type: Type of FlatCAM object that will be created from SVG
  6774. :param outname: The name given to the resulting FlatCAM object
  6775. :return:
  6776. """
  6777. self.defaults.report_usage("import_svg()")
  6778. log.debug("App.import_svg()")
  6779. obj_type = ""
  6780. if geo_type is None or geo_type == "geometry":
  6781. obj_type = "geometry"
  6782. elif geo_type == "gerber":
  6783. obj_type = "gerber"
  6784. else:
  6785. self.inform.emit('[ERROR_NOTCL] %s' %
  6786. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  6787. return
  6788. units = self.defaults['units'].upper()
  6789. def obj_init(geo_obj, app_obj):
  6790. geo_obj.import_svg(filename, obj_type, units=units)
  6791. geo_obj.multigeo = False
  6792. geo_obj.source_file = self.export_gerber(obj_name=name, filename=None, local_use=geo_obj, use_thread=False)
  6793. with self.proc_container.new(_("Importing SVG")) as proc:
  6794. # Object name
  6795. name = outname or filename.split('/')[-1].split('\\')[-1]
  6796. ret = self.app_obj.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  6797. if ret == 'fail':
  6798. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  6799. return 'fail'
  6800. # Register recent file
  6801. self.file_opened.emit("svg", filename)
  6802. # AppGUI feedback
  6803. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  6804. def import_dxf(self, filename, geo_type='geometry', outname=None, plot=True):
  6805. """
  6806. Adds a new Geometry Object to the projects and populates
  6807. it with shapes extracted from the DXF file.
  6808. :param filename: Path to the DXF file.
  6809. :param geo_type: Type of FlatCAM object that will be created from DXF
  6810. :param outname: Name for the imported Geometry
  6811. :param plot: If True then the resulting object will be plotted on canvas
  6812. :return:
  6813. """
  6814. self.defaults.report_usage("import_dxf()")
  6815. obj_type = ""
  6816. if geo_type is None or geo_type == "geometry":
  6817. obj_type = "geometry"
  6818. elif geo_type == "gerber":
  6819. obj_type = geo_type
  6820. else:
  6821. self.inform.emit('[ERROR_NOTCL] %s' %
  6822. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  6823. return
  6824. units = self.defaults['units'].upper()
  6825. def obj_init(geo_obj, app_obj):
  6826. geo_obj.import_dxf(filename, obj_type, units=units)
  6827. geo_obj.multigeo = False
  6828. with self.proc_container.new(_("Importing DXF")):
  6829. # Object name
  6830. name = outname or filename.split('/')[-1].split('\\')[-1]
  6831. ret = self.app_obj.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  6832. if ret == 'fail':
  6833. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  6834. return 'fail'
  6835. # Register recent file
  6836. self.file_opened.emit("dxf", filename)
  6837. # AppGUI feedback
  6838. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  6839. def open_gerber(self, filename, outname=None, plot=True, from_tcl=False):
  6840. """
  6841. Opens a Gerber file, parses it and creates a new object for
  6842. it in the program. Thread-safe.
  6843. :param outname: Name of the resulting object. None causes the
  6844. name to be that of the file. Str.
  6845. :param filename: Gerber file filename
  6846. :type filename: str
  6847. :param plot: boolean, to plot or not the resulting object
  6848. :param from_tcl: True if run from Tcl Shell
  6849. :return: None
  6850. """
  6851. # How the object should be initialized
  6852. def obj_init(gerber_obj, app_obj):
  6853. assert isinstance(gerber_obj, GerberObject), \
  6854. "Expected to initialize a GerberObject but got %s" % type(gerber_obj)
  6855. # Opening the file happens here
  6856. try:
  6857. gerber_obj.parse_file(filename)
  6858. except IOError:
  6859. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  6860. return "fail"
  6861. except ParseError as err:
  6862. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  6863. app_obj.log.error(str(err))
  6864. return "fail"
  6865. except Exception as e:
  6866. log.debug("App.open_gerber() --> %s" % str(e))
  6867. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  6868. msg += traceback.format_exc()
  6869. app_obj.inform.emit(msg)
  6870. return "fail"
  6871. if gerber_obj.is_empty():
  6872. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  6873. _("Object is not Gerber file or empty. Aborting object creation."))
  6874. return "fail"
  6875. App.log.debug("open_gerber()")
  6876. with self.proc_container.new(_("Opening Gerber")):
  6877. # Object name
  6878. name = outname or filename.split('/')[-1].split('\\')[-1]
  6879. # # ## Object creation # ##
  6880. ret_val = self.app_obj.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  6881. if ret_val == 'fail':
  6882. if from_tcl:
  6883. filename = self.defaults['global_tcl_path'] + '/' + name
  6884. ret_val = self.app_obj.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  6885. if ret_val == 'fail':
  6886. self.inform.emit('[ERROR_NOTCL]%s' % _('Open Gerber failed. Probable not a Gerber file.'))
  6887. return 'fail'
  6888. # Register recent file
  6889. self.file_opened.emit("gerber", filename)
  6890. # AppGUI feedback
  6891. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  6892. def open_excellon(self, filename, outname=None, plot=True, from_tcl=False):
  6893. """
  6894. Opens an Excellon file, parses it and creates a new object for
  6895. it in the program. Thread-safe.
  6896. :param outname: Name of the resulting object. None causes the name to be that of the file.
  6897. :param filename: Excellon file filename
  6898. :type filename: str
  6899. :param plot: boolean, to plot or not the resulting object
  6900. :param from_tcl: True if run from Tcl Shell
  6901. :return: None
  6902. """
  6903. App.log.debug("open_excellon()")
  6904. # How the object should be initialized
  6905. def obj_init(excellon_obj, app_obj):
  6906. try:
  6907. ret = excellon_obj.parse_file(filename=filename)
  6908. if ret == "fail":
  6909. log.debug("Excellon parsing failed.")
  6910. self.inform.emit('[ERROR_NOTCL] %s' %
  6911. _("This is not Excellon file."))
  6912. return "fail"
  6913. except IOError:
  6914. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  6915. (_("Cannot open file"), filename))
  6916. log.debug("Could not open Excellon object.")
  6917. return "fail"
  6918. except Exception:
  6919. msg = '[ERROR_NOTCL] %s' % \
  6920. _("An internal error has occurred. See shell.\n")
  6921. msg += traceback.format_exc()
  6922. app_obj.inform.emit(msg)
  6923. return "fail"
  6924. ret = excellon_obj.create_geometry()
  6925. if ret == 'fail':
  6926. log.debug("Could not create geometry for Excellon object.")
  6927. return "fail"
  6928. for tool in excellon_obj.tools:
  6929. if excellon_obj.tools[tool]['solid_geometry']:
  6930. return
  6931. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("No geometry found in file"), filename))
  6932. return "fail"
  6933. with self.proc_container.new(_("Opening Excellon.")):
  6934. # Object name
  6935. name = outname or filename.split('/')[-1].split('\\')[-1]
  6936. ret_val = self.app_obj.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  6937. if ret_val == 'fail':
  6938. if from_tcl:
  6939. filename = self.defaults['global_tcl_path'] + '/' + name
  6940. ret_val = self.app_obj.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  6941. if ret_val == 'fail':
  6942. self.inform.emit('[ERROR_NOTCL] %s' %
  6943. _('Open Excellon file failed. Probable not an Excellon file.'))
  6944. return
  6945. # Register recent file
  6946. self.file_opened.emit("excellon", filename)
  6947. # AppGUI feedback
  6948. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  6949. def open_gcode(self, filename, outname=None, force_parsing=None, plot=True, from_tcl=False):
  6950. """
  6951. Opens a G-gcode file, parses it and creates a new object for
  6952. it in the program. Thread-safe.
  6953. :param filename: G-code file filename
  6954. :param outname: Name of the resulting object. None causes the name to be that of the file.
  6955. :param force_parsing:
  6956. :param plot: If True plot the object on canvas
  6957. :param from_tcl: True if run from Tcl Shell
  6958. :return: None
  6959. """
  6960. App.log.debug("open_gcode()")
  6961. # How the object should be initialized
  6962. def obj_init(job_obj, app_obj_):
  6963. """
  6964. :param job_obj: the resulting object
  6965. :type app_obj_: App
  6966. """
  6967. assert isinstance(app_obj_, App), \
  6968. "Initializer expected App, got %s" % type(app_obj_)
  6969. app_obj_.inform.emit('%s...' % _("Reading GCode file"))
  6970. try:
  6971. f = open(filename)
  6972. gcode = f.read()
  6973. f.close()
  6974. except IOError:
  6975. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open"), filename))
  6976. return "fail"
  6977. job_obj.gcode = gcode
  6978. gcode_ret = job_obj.gcode_parse(force_parsing=force_parsing)
  6979. if gcode_ret == "fail":
  6980. self.inform.emit('[ERROR_NOTCL] %s' % _("This is not GCODE"))
  6981. return "fail"
  6982. job_obj.create_geometry()
  6983. with self.proc_container.new(_("Opening G-Code.")):
  6984. # Object name
  6985. name = outname or filename.split('/')[-1].split('\\')[-1]
  6986. # New object creation and file processing
  6987. ret_val = self.app_obj.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  6988. if ret_val == 'fail':
  6989. if from_tcl:
  6990. filename = self.defaults['global_tcl_path'] + '/' + name
  6991. ret_val = self.app_obj.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  6992. if ret_val == 'fail':
  6993. self.inform.emit('[ERROR_NOTCL] %s' %
  6994. _("Failed to create CNCJob Object. Probable not a GCode file. "
  6995. "Try to load it from File menu.\n "
  6996. "Attempting to create a FlatCAM CNCJob Object from "
  6997. "G-Code file failed during processing"))
  6998. return "fail"
  6999. # Register recent file
  7000. self.file_opened.emit("cncjob", filename)
  7001. # AppGUI feedback
  7002. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7003. def open_hpgl2(self, filename, outname=None):
  7004. """
  7005. Opens a HPGL2 file, parses it and creates a new object for
  7006. it in the program. Thread-safe.
  7007. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7008. :param filename: HPGL2 file filename
  7009. :return: None
  7010. """
  7011. filename = filename
  7012. # How the object should be initialized
  7013. def obj_init(geo_obj, app_obj):
  7014. assert isinstance(geo_obj, GeometryObject), \
  7015. "Expected to initialize a GeometryObject but got %s" % type(geo_obj)
  7016. # Opening the file happens here
  7017. obj = HPGL2(self)
  7018. try:
  7019. HPGL2.parse_file(obj, filename)
  7020. except IOError:
  7021. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7022. return "fail"
  7023. except ParseError as err:
  7024. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7025. app_obj.log.error(str(err))
  7026. return "fail"
  7027. except Exception as e:
  7028. log.debug("App.open_hpgl2() --> %s" % str(e))
  7029. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7030. msg += traceback.format_exc()
  7031. app_obj.inform.emit(msg)
  7032. return "fail"
  7033. geo_obj.multigeo = True
  7034. geo_obj.solid_geometry = deepcopy(obj.solid_geometry)
  7035. geo_obj.tools = deepcopy(obj.tools)
  7036. geo_obj.source_file = deepcopy(obj.source_file)
  7037. del obj
  7038. if not geo_obj.solid_geometry:
  7039. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  7040. _("Object is not HPGL2 file or empty. Aborting object creation."))
  7041. return "fail"
  7042. App.log.debug("open_hpgl2()")
  7043. with self.proc_container.new(_("Opening HPGL2")):
  7044. # Object name
  7045. name = outname or filename.split('/')[-1].split('\\')[-1]
  7046. # # ## Object creation # ##
  7047. ret = self.app_obj.new_object("geometry", name, obj_init, autoselected=False)
  7048. if ret == 'fail':
  7049. self.inform.emit('[ERROR_NOTCL]%s' % _(' Open HPGL2 failed. Probable not a HPGL2 file.'))
  7050. return 'fail'
  7051. # Register recent file
  7052. self.file_opened.emit("geometry", filename)
  7053. # AppGUI feedback
  7054. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7055. def open_script(self, filename, outname=None, silent=False):
  7056. """
  7057. Opens a Script file, parses it and creates a new object for
  7058. it in the program. Thread-safe.
  7059. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7060. :param filename: Script file filename
  7061. :param silent: If True there will be no messages printed to StatusBar
  7062. :return: None
  7063. """
  7064. def obj_init(script_obj, app_obj):
  7065. assert isinstance(script_obj, ScriptObject), \
  7066. "Expected to initialize a ScriptObject but got %s" % type(script_obj)
  7067. if silent is False:
  7068. app_obj.inform.emit('[success] %s' % _("TCL script file opened in Code Editor."))
  7069. try:
  7070. script_obj.parse_file(filename)
  7071. except IOError:
  7072. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7073. return "fail"
  7074. except ParseError as err:
  7075. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7076. app_obj.log.error(str(err))
  7077. return "fail"
  7078. except Exception as e:
  7079. log.debug("App.open_script() -> %s" % str(e))
  7080. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7081. msg += traceback.format_exc()
  7082. app_obj.inform.emit(msg)
  7083. return "fail"
  7084. App.log.debug("open_script()")
  7085. with self.proc_container.new(_("Opening TCL Script...")):
  7086. # Object name
  7087. script_name = outname or filename.split('/')[-1].split('\\')[-1]
  7088. # Object creation
  7089. ret_val = self.app_obj.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  7090. if ret_val == 'fail':
  7091. filename = self.defaults['global_tcl_path'] + '/' + script_name
  7092. ret_val = self.app_obj.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  7093. if ret_val == 'fail':
  7094. self.inform.emit('[ERROR_NOTCL]%s' % _('Failed to open TCL Script.'))
  7095. return 'fail'
  7096. # Register recent file
  7097. self.file_opened.emit("script", filename)
  7098. # AppGUI feedback
  7099. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7100. def open_config_file(self, filename, run_from_arg=None):
  7101. """
  7102. Loads a config file from the specified file.
  7103. :param filename: Name of the file from which to load.
  7104. :param run_from_arg: if True the FlatConfig file will be open as an command line argument
  7105. :return: None
  7106. """
  7107. App.log.debug("Opening config file: " + filename)
  7108. if run_from_arg:
  7109. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7110. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7111. _("Opening FlatCAM Config file.")),
  7112. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7113. color=QtGui.QColor("gray"))
  7114. # # add the tab if it was closed
  7115. # self.ui.plot_tab_area.addTab(self.ui.text_editor_tab, _("Code Editor"))
  7116. # # first clear previous text in text editor (if any)
  7117. # self.ui.text_editor_tab.code_editor.clear()
  7118. #
  7119. # # Switch plot_area to CNCJob tab
  7120. # self.ui.plot_tab_area.setCurrentWidget(self.ui.text_editor_tab)
  7121. # close the Code editor if already open
  7122. if self.toggle_codeeditor:
  7123. self.on_toggle_code_editor()
  7124. self.on_toggle_code_editor()
  7125. try:
  7126. if filename:
  7127. f = QtCore.QFile(filename)
  7128. if f.open(QtCore.QIODevice.ReadOnly):
  7129. stream = QtCore.QTextStream(f)
  7130. code_edited = stream.readAll()
  7131. self.text_editor_tab.code_editor.setPlainText(code_edited)
  7132. f.close()
  7133. except IOError:
  7134. App.log.error("Failed to open config file: %s" % filename)
  7135. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  7136. (_("Failed to open config file"), filename))
  7137. return
  7138. def open_project(self, filename, run_from_arg=None, plot=True, cli=None, from_tcl=False):
  7139. """
  7140. Loads a project from the specified file.
  7141. 1) Loads and parses file
  7142. 2) Registers the file as recently opened.
  7143. 3) Calls on_file_new()
  7144. 4) Updates options
  7145. 5) Calls app_obj.new_object() with the object's from_dict() as init method.
  7146. 6) Calls plot_all() if plot=True
  7147. :param filename: Name of the file from which to load.
  7148. :param run_from_arg: True if run for arguments
  7149. :param plot: If True plot all objects in the project
  7150. :param cli: Run from command line
  7151. :param from_tcl: True if run from Tcl Sehll
  7152. :return: None
  7153. """
  7154. App.log.debug("Opening project: " + filename)
  7155. # block autosaving while a project is loaded
  7156. self.block_autosave = True
  7157. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7158. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7159. if cli is None:
  7160. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  7161. if run_from_arg:
  7162. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7163. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7164. _("Opening FlatCAM Project file.")),
  7165. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7166. color=QtGui.QColor("gray"))
  7167. # Open and parse an uncompressed Project file
  7168. try:
  7169. f = open(filename, 'r')
  7170. except IOError:
  7171. if from_tcl:
  7172. name = filename.split('/')[-1].split('\\')[-1]
  7173. filename = self.defaults['global_tcl_path'] + '/' + name
  7174. try:
  7175. f = open(filename, 'r')
  7176. except IOError:
  7177. log.error("Failed to open project file: %s" % filename)
  7178. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7179. return
  7180. else:
  7181. log.error("Failed to open project file: %s" % filename)
  7182. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7183. return
  7184. try:
  7185. d = json.load(f, object_hook=dict2obj)
  7186. except Exception as e:
  7187. log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  7188. (filename, str(e)))
  7189. f.close()
  7190. # Open and parse a compressed Project file
  7191. try:
  7192. with lzma.open(filename) as f:
  7193. file_content = f.read().decode('utf-8')
  7194. d = json.loads(file_content, object_hook=dict2obj)
  7195. except Exception as e:
  7196. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  7197. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7198. return
  7199. # Clear the current project
  7200. # # NOT THREAD SAFE # ##
  7201. if run_from_arg is True:
  7202. pass
  7203. elif cli is True:
  7204. self.delete_selection_shape()
  7205. else:
  7206. self.on_file_new()
  7207. # Project options
  7208. self.options.update(d['options'])
  7209. self.project_filename = filename
  7210. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7211. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7212. if cli is None:
  7213. self.set_screen_units(self.options["units"])
  7214. # Re create objects
  7215. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  7216. for obj in d['objs']:
  7217. try:
  7218. def obj_init(obj_inst, app_inst):
  7219. obj_inst.from_dict(obj)
  7220. App.log.debug("Recreating from opened project an %s object: %s" %
  7221. (obj['kind'].capitalize(), obj['options']['name']))
  7222. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7223. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7224. if cli is None:
  7225. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"),
  7226. obj['kind'].upper(),
  7227. obj['options']['name']
  7228. )
  7229. )
  7230. self.app_obj.new_object(obj['kind'], obj['options']['name'], obj_init, plot=plot)
  7231. except Exception as e:
  7232. print('App.open_project() --> ' + str(e))
  7233. self.inform.emit('[success] %s: %s' % (_("Project loaded from"), filename))
  7234. self.should_we_save = False
  7235. self.file_opened.emit("project", filename)
  7236. # restore autosaving after a project was loaded
  7237. self.block_autosave = False
  7238. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7239. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7240. if cli is None:
  7241. self.set_ui_title(name=self.project_filename)
  7242. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  7243. def plot_all(self, fit_view=True, muted=False, use_thread=True):
  7244. """
  7245. Re-generates all plots from all objects.
  7246. :param fit_view: if True will plot the objects and will adjust the zoom to fit all plotted objects into view
  7247. :param muted: if True don't print messages
  7248. :param use_thread: if True will use threading for plotting the objects
  7249. :return: None
  7250. """
  7251. self.log.debug("Plot_all()")
  7252. if muted is not True:
  7253. self.inform.emit('[success] %s...' % _("Redrawing all objects"))
  7254. for plot_obj in self.collection.get_list():
  7255. def worker_task(obj):
  7256. with self.proc_container.new("Plotting"):
  7257. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  7258. if fit_view is True:
  7259. self.app_obj.object_plotted.emit(obj)
  7260. if use_thread is True:
  7261. # Send to worker
  7262. self.worker_task.emit({'fcn': worker_task, 'params': [plot_obj]})
  7263. else:
  7264. worker_task(plot_obj)
  7265. def register_folder(self, filename):
  7266. """
  7267. Register the last folder used by the app to open something
  7268. :param filename: the last folder is extracted from the filename
  7269. :return: None
  7270. """
  7271. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  7272. def register_save_folder(self, filename):
  7273. """
  7274. Register the last folder used by the app to save something
  7275. :param filename: the last folder is extracted from the filename
  7276. :return: None
  7277. """
  7278. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  7279. # def set_progress_bar(self, percentage, text=""):
  7280. # """
  7281. # Set a progress bar to a value (percentage)
  7282. #
  7283. # :param percentage: Value set to the progressbar
  7284. # :param text: Not used
  7285. # :return: None
  7286. # """
  7287. # self.ui.progress_bar.setValue(int(percentage))
  7288. def setup_recent_items(self):
  7289. """
  7290. Setup a dictionary with the recent files accessed, organized by type
  7291. :return:
  7292. """
  7293. icons = {
  7294. "gerber": self.resource_location + "/flatcam_icon16.png",
  7295. "excellon": self.resource_location + "/drill16.png",
  7296. 'geometry': self.resource_location + "/geometry16.png",
  7297. "cncjob": self.resource_location + "/cnc16.png",
  7298. "script": self.resource_location + "/script_new24.png",
  7299. "document": self.resource_location + "/notes16_1.png",
  7300. "project": self.resource_location + "/project16.png",
  7301. "svg": self.resource_location + "/geometry16.png",
  7302. "dxf": self.resource_location + "/dxf16.png",
  7303. "pdf": self.resource_location + "/pdf32.png",
  7304. "image": self.resource_location + "/image16.png"
  7305. }
  7306. try:
  7307. image_opener = self.image_tool.import_image
  7308. except AttributeError:
  7309. image_opener = None
  7310. openers = {
  7311. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  7312. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  7313. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  7314. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  7315. "script": lambda fname: self.worker_task.emit({'fcn': self.open_script, 'params': [fname]}),
  7316. "document": None,
  7317. 'project': self.open_project,
  7318. 'svg': self.import_svg,
  7319. 'dxf': self.import_dxf,
  7320. 'image': image_opener,
  7321. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  7322. }
  7323. # Open recent file for files
  7324. try:
  7325. f = open(self.data_path + '/recent.json')
  7326. except IOError:
  7327. App.log.error("Failed to load recent item list.")
  7328. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent item list."))
  7329. return
  7330. try:
  7331. self.recent = json.load(f)
  7332. except json.errors.JSONDecodeError:
  7333. App.log.error("Failed to parse recent item list.")
  7334. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent item list."))
  7335. f.close()
  7336. return
  7337. f.close()
  7338. # Open recent file for projects
  7339. try:
  7340. fp = open(self.data_path + '/recent_projects.json')
  7341. except IOError:
  7342. App.log.error("Failed to load recent project item list.")
  7343. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent projects item list."))
  7344. return
  7345. try:
  7346. self.recent_projects = json.load(fp)
  7347. except json.errors.JSONDecodeError:
  7348. App.log.error("Failed to parse recent project item list.")
  7349. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent project item list."))
  7350. fp.close()
  7351. return
  7352. fp.close()
  7353. # Closure needed to create callbacks in a loop.
  7354. # Otherwise late binding occurs.
  7355. def make_callback(func, fname):
  7356. def opener():
  7357. func(fname)
  7358. return opener
  7359. def reset_recent_files():
  7360. # Reset menu
  7361. self.ui.recent.clear()
  7362. self.recent = []
  7363. try:
  7364. ff = open(self.data_path + '/recent.json', 'w')
  7365. except IOError:
  7366. App.log.error("Failed to open recent items file for writing.")
  7367. return
  7368. json.dump(self.recent, ff)
  7369. def reset_recent_projects():
  7370. # Reset menu
  7371. self.ui.recent_projects.clear()
  7372. self.recent_projects = []
  7373. try:
  7374. frp = open(self.data_path + '/recent_projects.json', 'w')
  7375. except IOError:
  7376. App.log.error("Failed to open recent projects items file for writing.")
  7377. return
  7378. json.dump(self.recent, frp)
  7379. # Reset menu
  7380. self.ui.recent.clear()
  7381. self.ui.recent_projects.clear()
  7382. # Create menu items for projects
  7383. for recent in self.recent_projects:
  7384. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  7385. if recent['kind'] == 'project':
  7386. try:
  7387. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  7388. # Attach callback
  7389. o = make_callback(openers[recent["kind"]], recent['filename'])
  7390. action.triggered.connect(o)
  7391. self.ui.recent_projects.addAction(action)
  7392. except KeyError:
  7393. App.log.error("Unsupported file type: %s" % recent["kind"])
  7394. # Last action in Recent Files menu is one that Clear the content
  7395. clear_action_proj = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  7396. (_("Clear Recent projects")), self)
  7397. clear_action_proj.triggered.connect(reset_recent_projects)
  7398. self.ui.recent_projects.addSeparator()
  7399. self.ui.recent_projects.addAction(clear_action_proj)
  7400. # Create menu items for files
  7401. for recent in self.recent:
  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.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 = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  7414. (_("Clear Recent files")), self)
  7415. clear_action.triggered.connect(reset_recent_files)
  7416. self.ui.recent.addSeparator()
  7417. self.ui.recent.addAction(clear_action)
  7418. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  7419. # self.ui.menufilerecent.set_submenu(recent_menu)
  7420. # recent_menu.show_all()
  7421. # self.ui.recent.show()
  7422. self.log.debug("Recent items list has been populated.")
  7423. def setup_component_editor(self):
  7424. """
  7425. Default text for the Selected tab when is not taken by the Object UI.
  7426. :return:
  7427. """
  7428. # label = QtWidgets.QLabel("Choose an item from Project")
  7429. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  7430. sel_title = QtWidgets.QTextEdit(
  7431. _('<b>Shortcut Key List</b>'))
  7432. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  7433. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  7434. f_settings = QSettings("Open Source", "FlatCAM")
  7435. if f_settings.contains("notebook_font_size"):
  7436. fsize = f_settings.value('notebook_font_size', type=int)
  7437. else:
  7438. fsize = 12
  7439. tsize = fsize + int(fsize / 2)
  7440. # selected_text = (_('''
  7441. # <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span>
  7442. # </p>
  7443. #
  7444. # <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  7445. # The normal flow when working in FlatCAM is the following:</span></p>
  7446. #
  7447. # <ol>
  7448. # <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG
  7449. # file into
  7450. # FlatCAM using either the menu&#39;s, toolbars, key shortcuts or
  7451. # even dragging and dropping the files on the AppGUI.<br />
  7452. # <br />
  7453. # You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp;
  7454. # drop of the
  7455. # file into the FLATCAM AppGUI or through the menu/toolbar links offered within the app.</span><br />
  7456. # &nbsp;</li>
  7457. # <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it
  7458. # and then
  7459. # focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the
  7460. # Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to
  7461. # it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  7462. # <br />
  7463. # If the selection of the object is done on the canvas by single click instead, and the
  7464. # <strong>SELECTED TAB</strong>
  7465. # is in focus, again the object properties will be displayed into the Selected Tab. Alternatively,
  7466. # double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate
  7467. # it even if it was out of focus.<br />
  7468. # <br />
  7469. # You can change the parameters in this screen and the flow direction is like this:<br />
  7470. # <br />
  7471. # <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;
  7472. # <strong> Geometry Object
  7473. # </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object
  7474. # </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in
  7475. # <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  7476. # </ol>
  7477. #
  7478. # <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in
  7479. # <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut:
  7480. # <strong>F3</strong>.</span></p>
  7481. #
  7482. # ''').format(fsize=fsize, tsize=tsize))
  7483. selected_text = '''
  7484. <p><span style="font-size:{tsize}px"><strong>{title}</strong></span></p>
  7485. <p><span style="font-size:{fsize}px"><strong>{subtitle}</strong>:<br />
  7486. {s1}</span></p>
  7487. <ol>
  7488. <li><span style="font-size:{fsize}px">{s2}<br />
  7489. <br />
  7490. {s3}</span><br />
  7491. &nbsp;</li>
  7492. <li><span style="font-size:{fsize}px">{s4}<br />
  7493. &nbsp;</li>
  7494. <br />
  7495. <li><span style="font-size:{fsize}px">{s5}<br />
  7496. &nbsp;</li>
  7497. <br />
  7498. <li><span style="font-size:{fsize}px">{s6}<br />
  7499. <br />
  7500. {s7}</span></li>
  7501. </ol>
  7502. <p><span style="font-size:{fsize}px">{s8}</span></p>
  7503. '''.format(
  7504. title=_("Selected Tab - Choose an Item from Project Tab"),
  7505. subtitle=_("Details"),
  7506. s1=_("The normal flow when working in FlatCAM is the following:"),
  7507. s2=_("Load/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM "
  7508. "using either the toolbars, key shortcuts or even dragging and dropping the "
  7509. "files on the AppGUI."),
  7510. s3=_("You can also load a FlatCAM project by double clicking on the project file, "
  7511. "drag and drop of the file into the FLATCAM AppGUI or through the menu (or toolbar) "
  7512. "actions offered within the app."),
  7513. s4=_("Once an object is available in the Project Tab, by selecting it and then focusing "
  7514. "on SELECTED TAB (more simpler is to double click the object name in the Project Tab, "
  7515. "SELECTED TAB will be updated with the object properties according to its kind: "
  7516. "Gerber, Excellon, Geometry or CNCJob object."),
  7517. s5=_("If the selection of the object is done on the canvas by single click instead, "
  7518. "and the SELECTED TAB is in focus, again the object properties will be displayed into the "
  7519. "Selected Tab. Alternatively, double clicking on the object on the canvas will bring "
  7520. "the SELECTED TAB and populate it even if it was out of focus."),
  7521. s6=_("You can change the parameters in this screen and the flow direction is like this:"),
  7522. s7=_("Gerber/Excellon Object --> Change Parameter --> Generate Geometry --> Geometry Object --> "
  7523. "Add tools (change param in Selected Tab) --> Generate CNCJob --> CNCJob Object --> "
  7524. "Verify GCode (through Edit CNC Code) and/or append/prepend to GCode "
  7525. "(again, done in SELECTED TAB) --> Save GCode."),
  7526. s8=_("A list of key shortcuts is available through an menu entry in Help --> Shortcuts List "
  7527. "or through its own key shortcut: <b>F3</b>."),
  7528. tsize=tsize,
  7529. fsize=fsize
  7530. )
  7531. sel_title.setText(selected_text)
  7532. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  7533. self.ui.selected_scroll_area.setWidget(sel_title)
  7534. def setup_obj_classes(self):
  7535. """
  7536. Sets up application specifics on the FlatCAMObj class. This way the object.app attribute will point to the App
  7537. class.
  7538. :return: None
  7539. """
  7540. FlatCAMObj.app = self
  7541. ObjectCollection.app = self
  7542. Gerber.app = self
  7543. Excellon.app = self
  7544. Geometry.app = self
  7545. CNCjob.app = self
  7546. FCProcess.app = self
  7547. FCProcessContainer.app = self
  7548. OptionsGroupUI.app = self
  7549. def version_check(self):
  7550. """
  7551. Checks for the latest version of the program. Alerts the
  7552. user if theirs is outdated. This method is meant to be run
  7553. in a separate thread.
  7554. :return: None
  7555. """
  7556. self.log.debug("version_check()")
  7557. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  7558. full_url = "%s?s=%s&v=%s&os=%s&%s" % (
  7559. App.version_url,
  7560. str(self.defaults['global_serial']),
  7561. str(self.version),
  7562. str(self.os),
  7563. urllib.parse.urlencode(self.defaults["global_stats"])
  7564. )
  7565. # full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + \
  7566. # "&v=" + str(self.version) + "&os=" + str(self.os) + "&" + \
  7567. # urllib.parse.urlencode(self.defaults["global_stats"])
  7568. else:
  7569. # no_stats dict; just so it won't break things on website
  7570. no_ststs_dict = {}
  7571. no_ststs_dict["global_ststs"] = {}
  7572. full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + "&v=" + str(self.version)
  7573. full_url += "&os=" + str(self.os) + "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  7574. App.log.debug("Checking for updates @ %s" % full_url)
  7575. # ## Get the data
  7576. try:
  7577. f = urllib.request.urlopen(full_url)
  7578. except Exception:
  7579. # App.log.warning("Failed checking for latest version. Could not connect.")
  7580. self.log.warning("Failed checking for latest version. Could not connect.")
  7581. self.inform.emit('[WARNING_NOTCL] %s' % _("Failed checking for latest version. Could not connect."))
  7582. return
  7583. try:
  7584. data = json.load(f)
  7585. except Exception as e:
  7586. App.log.error("Could not parse information about latest version.")
  7587. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not parse information about latest version."))
  7588. App.log.debug("json.load(): %s" % str(e))
  7589. f.close()
  7590. return
  7591. f.close()
  7592. # ## Latest version?
  7593. if self.version >= data["version"]:
  7594. App.log.debug("FlatCAM is up to date!")
  7595. self.inform.emit('[success] %s' % _("FlatCAM is up to date!"))
  7596. return
  7597. App.log.debug("Newer version available.")
  7598. self.message.emit(
  7599. _("Newer Version Available"),
  7600. '%s<br><br>><b>%s</b><br>%s' % (
  7601. _("There is a newer version of FlatCAM available for download:"),
  7602. str(data["name"]),
  7603. str(data["message"])
  7604. ),
  7605. _("info")
  7606. )
  7607. def on_plotcanvas_setup(self, container=None):
  7608. """
  7609. This is doing the setup for the plot area (canvas).
  7610. :param container: QT Widget where to install the canvas
  7611. :return: None
  7612. """
  7613. if container:
  7614. plot_container = container
  7615. else:
  7616. plot_container = self.ui.right_layout
  7617. modifier = QtWidgets.QApplication.queryKeyboardModifiers()
  7618. if self.is_legacy is True or modifier == QtCore.Qt.ControlModifier:
  7619. self.is_legacy = True
  7620. self.defaults["global_graphic_engine"] = "2D"
  7621. self.plotcanvas = PlotCanvasLegacy(plot_container, self)
  7622. else:
  7623. try:
  7624. self.plotcanvas = PlotCanvas(plot_container, self)
  7625. except Exception as er:
  7626. msg_txt = traceback.format_exc()
  7627. log.debug("App.on_plotcanvas_setup() failed -> %s" % str(er))
  7628. log.debug("OpenGL canvas initialization failed with the following error.\n" + msg_txt)
  7629. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  7630. msg += _("OpenGL canvas initialization failed. HW or HW configuration not supported."
  7631. "Change the graphic engine to Legacy(2D) in Edit -> Preferences -> General tab.\n\n")
  7632. msg += msg_txt
  7633. self.inform.emit(msg)
  7634. return 'fail'
  7635. # So it can receive key presses
  7636. self.plotcanvas.native.setFocus()
  7637. if self.is_legacy is False:
  7638. pan_button = 2 if self.defaults["global_pan_button"] == '2' else 3
  7639. # Set the mouse button for panning
  7640. self.plotcanvas.view.camera.pan_button_setting = pan_button
  7641. self.mm = self.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move_over_plot)
  7642. self.mp = self.plotcanvas.graph_event_connect('mouse_press', self.on_mouse_click_over_plot)
  7643. self.mr = self.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release_over_plot)
  7644. self.mdc = self.plotcanvas.graph_event_connect('mouse_double_click', self.on_mouse_double_click_over_plot)
  7645. # Keys over plot enabled
  7646. self.kp = self.plotcanvas.graph_event_connect('key_press', self.ui.keyPressEvent)
  7647. if self.defaults['global_cursor_type'] == 'small':
  7648. self.app_cursor = self.plotcanvas.new_cursor()
  7649. else:
  7650. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  7651. if self.ui.grid_snap_btn.isChecked():
  7652. self.app_cursor.enabled = True
  7653. else:
  7654. self.app_cursor.enabled = False
  7655. if self.is_legacy is False:
  7656. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  7657. else:
  7658. # will use the default Matplotlib axes
  7659. self.hover_shapes = ShapeCollectionLegacy(obj=self, app=self, name='hover')
  7660. def on_zoom_fit(self):
  7661. """
  7662. Callback for zoom-fit request. This can be either from the corresponding
  7663. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  7664. with axes limits from the geometry bounds of all objects.
  7665. :return: None
  7666. """
  7667. if self.is_legacy is False:
  7668. self.plotcanvas.fit_view()
  7669. else:
  7670. xmin, ymin, xmax, ymax = self.collection.get_bounds()
  7671. width = xmax - xmin
  7672. height = ymax - ymin
  7673. xmin -= 0.05 * width
  7674. xmax += 0.05 * width
  7675. ymin -= 0.05 * height
  7676. ymax += 0.05 * height
  7677. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  7678. def on_zoom_in(self):
  7679. """
  7680. Callback for zoom-in request.
  7681. :return:
  7682. """
  7683. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  7684. def on_zoom_out(self):
  7685. """
  7686. Callback for zoom-out request.
  7687. :return:
  7688. """
  7689. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  7690. def disable_all_plots(self):
  7691. self.defaults.report_usage("disable_all_plots()")
  7692. self.disable_plots(self.collection.get_list())
  7693. self.inform.emit('[success] %s' %
  7694. _("All plots disabled."))
  7695. def disable_other_plots(self):
  7696. self.defaults.report_usage("disable_other_plots()")
  7697. self.disable_plots(self.collection.get_non_selected())
  7698. self.inform.emit('[success] %s' %
  7699. _("All non selected plots disabled."))
  7700. def enable_all_plots(self):
  7701. self.defaults.report_usage("enable_all_plots()")
  7702. self.enable_plots(self.collection.get_list())
  7703. self.inform.emit('[success] %s' %
  7704. _("All plots enabled."))
  7705. def on_enable_sel_plots(self):
  7706. log.debug("App.on_enable_sel_plot()")
  7707. object_list = self.collection.get_selected()
  7708. self.enable_plots(objects=object_list)
  7709. self.inform.emit('[success] %s' % _("Selected plots enabled..."))
  7710. def on_disable_sel_plots(self):
  7711. log.debug("App.on_disable_sel_plot()")
  7712. # self.inform.emit(_("Disabling plots ..."))
  7713. object_list = self.collection.get_selected()
  7714. self.disable_plots(objects=object_list)
  7715. self.inform.emit('[success] %s' % _("Selected plots disabled..."))
  7716. def enable_plots(self, objects):
  7717. """
  7718. Enable plots
  7719. :param objects: list of Objects to be enabled
  7720. :return:
  7721. """
  7722. log.debug("Enabling plots ...")
  7723. # self.inform.emit(_("Working ..."))
  7724. for obj in objects:
  7725. if obj.options['plot'] is False:
  7726. obj.options.set_change_callback(lambda x: None)
  7727. obj.options['plot'] = True
  7728. try:
  7729. # only the Gerber obj has on_plot_cb_click() method
  7730. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  7731. # disable this cb while disconnected,
  7732. # in case the operation takes time the user is not allowed to change it
  7733. obj.ui.plot_cb.setDisabled(True)
  7734. except AttributeError:
  7735. pass
  7736. obj.set_form_item("plot")
  7737. try:
  7738. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  7739. obj.ui.plot_cb.setDisabled(False)
  7740. except AttributeError:
  7741. pass
  7742. obj.options.set_change_callback(obj.on_options_change)
  7743. def worker_task(objs):
  7744. with self.proc_container.new(_("Enabling plots ...")):
  7745. for plot_obj in objs:
  7746. # obj.options['plot'] = True
  7747. if isinstance(plot_obj, CNCJobObject):
  7748. plot_obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  7749. else:
  7750. plot_obj.plot(visible=True)
  7751. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  7752. def disable_plots(self, objects):
  7753. """
  7754. Disables plots
  7755. :param objects: list of Objects to be disabled
  7756. :return:
  7757. """
  7758. # if no objects selected then do nothing
  7759. if not self.collection.get_selected():
  7760. return
  7761. log.debug("Disabling plots ...")
  7762. # self.inform.emit(_("Working ..."))
  7763. for obj in objects:
  7764. if obj.options['plot'] is True:
  7765. obj.options.set_change_callback(lambda x: None)
  7766. obj.options['plot'] = False
  7767. try:
  7768. # only the Gerber obj has on_plot_cb_click() method
  7769. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  7770. obj.ui.plot_cb.setDisabled(True)
  7771. except AttributeError:
  7772. pass
  7773. obj.set_form_item("plot")
  7774. try:
  7775. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  7776. obj.ui.plot_cb.setDisabled(False)
  7777. except AttributeError:
  7778. pass
  7779. obj.options.set_change_callback(obj.on_options_change)
  7780. try:
  7781. self.delete_selection_shape()
  7782. except Exception as e:
  7783. log.debug("App.disable_plots() --> %s" % str(e))
  7784. def worker_task(objs):
  7785. with self.proc_container.new(_("Disabling plots ...")):
  7786. for plot_obj in objs:
  7787. # obj.options['plot'] = True
  7788. if isinstance(plot_obj, CNCJobObject):
  7789. plot_obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  7790. else:
  7791. plot_obj.plot(visible=False)
  7792. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  7793. def toggle_plots(self, objects):
  7794. """
  7795. Toggle plots visibility
  7796. :param objects: list of Objects for which to be toggled the visibility
  7797. :return: None
  7798. """
  7799. # if no objects selected then do nothing
  7800. if not self.collection.get_selected():
  7801. return
  7802. log.debug("Toggling plots ...")
  7803. self.inform.emit(_("Working ..."))
  7804. for obj in objects:
  7805. if obj.options['plot'] is False:
  7806. obj.options['plot'] = True
  7807. else:
  7808. obj.options['plot'] = False
  7809. self.app_obj.plots_updated.emit()
  7810. def clear_plots(self):
  7811. """
  7812. Clear the plots
  7813. :return: None
  7814. """
  7815. objects = self.collection.get_list()
  7816. for obj in objects:
  7817. obj.clear(obj == objects[-1])
  7818. # Clear pool to free memory
  7819. self.clear_pool()
  7820. def on_set_color_action_triggered(self):
  7821. """
  7822. This slot gets called by clicking on the menu entry in the Set Color submenu of the context menu in Project Tab
  7823. :return:
  7824. """
  7825. new_color = self.defaults['gerber_plot_fill']
  7826. clicked_action = self.sender()
  7827. assert isinstance(clicked_action, QAction), "Expected a QAction, got %s" % type(clicked_action)
  7828. act_name = clicked_action.text()
  7829. sel_obj_list = self.collection.get_selected()
  7830. if not sel_obj_list:
  7831. return
  7832. # a default value, I just chose this one
  7833. alpha_level = 'BF'
  7834. for sel_obj in sel_obj_list:
  7835. if sel_obj.kind == 'excellon':
  7836. alpha_level = str(hex(
  7837. self.ui.excellon_defaults_form.excellon_gen_group.color_alpha_slider.value())[2:])
  7838. elif sel_obj.kind == 'gerber':
  7839. alpha_level = str(hex(self.ui.gerber_defaults_form.gerber_gen_group.pf_color_alpha_slider.value())[2:])
  7840. elif sel_obj.kind == 'geometry':
  7841. alpha_level = 'FF'
  7842. else:
  7843. log.debug(
  7844. "App.on_set_color_action_triggered() --> Default alpfa for this object type not supported yet")
  7845. continue
  7846. sel_obj.alpha_level = alpha_level
  7847. if act_name == _('Red'):
  7848. new_color = '#FF0000' + alpha_level
  7849. if act_name == _('Blue'):
  7850. new_color = '#0000FF' + alpha_level
  7851. if act_name == _('Yellow'):
  7852. new_color = '#FFDF00' + alpha_level
  7853. if act_name == _('Green'):
  7854. new_color = '#00FF00' + alpha_level
  7855. if act_name == _('Purple'):
  7856. new_color = '#FF00FF' + alpha_level
  7857. if act_name == _('Brown'):
  7858. new_color = '#A52A2A' + alpha_level
  7859. if act_name == _('White'):
  7860. new_color = '#FFFFFF' + alpha_level
  7861. if act_name == _('Black'):
  7862. new_color = '#000000' + alpha_level
  7863. if act_name == _('Custom'):
  7864. new_color = QtGui.QColor(self.defaults['gerber_plot_fill'][:7])
  7865. c_dialog = QtWidgets.QColorDialog()
  7866. plot_fill_color = c_dialog.getColor(initial=new_color)
  7867. if plot_fill_color.isValid() is False:
  7868. return
  7869. new_color = str(plot_fill_color.name()) + alpha_level
  7870. if act_name == _("Default"):
  7871. for sel_obj in sel_obj_list:
  7872. if sel_obj.kind == 'excellon':
  7873. new_color = self.defaults['excellon_plot_fill']
  7874. new_line_color = self.defaults['excellon_plot_line']
  7875. elif sel_obj.kind == 'gerber':
  7876. new_color = self.defaults['gerber_plot_fill']
  7877. new_line_color = self.defaults['gerber_plot_line']
  7878. elif sel_obj.kind == 'geometry':
  7879. new_color = self.defaults['geometry_plot_line']
  7880. new_line_color = self.defaults['geometry_plot_line']
  7881. else:
  7882. log.debug(
  7883. "App.on_set_color_action_triggered() --> Default color for this object type not supported yet")
  7884. continue
  7885. sel_obj.fill_color = new_color
  7886. sel_obj.outline_color = new_line_color
  7887. sel_obj.shapes.redraw(
  7888. update_colors=(new_color, new_line_color)
  7889. )
  7890. return
  7891. if act_name == _("Opacity"):
  7892. alpha_level, ok_button = QtWidgets.QInputDialog.getInt(
  7893. self.ui, _("Set alpha level ..."), '%s:' % _("Value"), min=0, max=255, step=1, value=191)
  7894. if ok_button:
  7895. alpha_str = str(hex(alpha_level)[2:]) if alpha_level != 0 else '00'
  7896. for sel_obj in sel_obj_list:
  7897. sel_obj.fill_color = sel_obj.fill_color[:-2] + alpha_str
  7898. sel_obj.shapes.redraw(
  7899. update_colors=(sel_obj.fill_color, sel_obj.outline_color)
  7900. )
  7901. return
  7902. new_line_color = color_variant(new_color[:7], 0.7)
  7903. if act_name == _("White"):
  7904. new_line_color = color_variant("#dedede", 0.7)
  7905. for sel_obj in sel_obj_list:
  7906. sel_obj.fill_color = new_color
  7907. sel_obj.outline_color = new_line_color
  7908. sel_obj.shapes.redraw(
  7909. update_colors=(new_color, new_line_color)
  7910. )
  7911. def generate_cnc_job(self, objects):
  7912. """
  7913. Slot that will be called by clicking an entry in the contextual menu generated in the Project Tab tree
  7914. :param objects: Selected objects in the Project Tab
  7915. :return:
  7916. """
  7917. self.defaults.report_usage("generate_cnc_job()")
  7918. # for obj in objects:
  7919. # obj.generatecncjob()
  7920. for obj in objects:
  7921. obj.on_generatecnc_button_click()
  7922. def save_project(self, filename, quit_action=False, silent=False, from_tcl=False):
  7923. """
  7924. Saves the current project to the specified file.
  7925. :param filename: Name of the file in which to save.
  7926. :type filename: str
  7927. :param quit_action: if the project saving will be followed by an app quit; boolean
  7928. :param silent: if True will not display status messages
  7929. :param from_tcl True is run from Tcl Shell
  7930. :return: None
  7931. """
  7932. self.log.debug("save_project()")
  7933. self.save_in_progress = True
  7934. with self.proc_container.new(_("Saving FlatCAM Project")):
  7935. # Capture the latest changes
  7936. # Current object
  7937. try:
  7938. current_object = self.collection.get_active()
  7939. if current_object:
  7940. current_object.read_form()
  7941. except Exception as e:
  7942. self.log.debug("save_project() --> There was no active object. Skipping read_form. %s" % str(e))
  7943. pass
  7944. # Serialize the whole project
  7945. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  7946. "options": self.options,
  7947. "version": self.version}
  7948. if self.defaults["global_save_compressed"] is True:
  7949. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  7950. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  7951. # # Write
  7952. f.write(g)
  7953. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  7954. else:
  7955. # Open file
  7956. try:
  7957. f = open(filename, 'w')
  7958. except IOError:
  7959. App.log.error("Failed to open file for saving: %s", filename)
  7960. self.inform.emit('[ERROR_NOTCL] %s' % _("The object is used by another application."))
  7961. return
  7962. # Write
  7963. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  7964. f.close()
  7965. # verification of the saved project
  7966. # Open and parse
  7967. try:
  7968. saved_f = open(filename, 'r')
  7969. except IOError:
  7970. if silent is False:
  7971. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  7972. (_("Failed to verify project file"), filename, _("Retry to save it.")))
  7973. return
  7974. try:
  7975. saved_d = json.load(saved_f, object_hook=dict2obj)
  7976. except Exception:
  7977. if silent is False:
  7978. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  7979. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  7980. f.close()
  7981. return
  7982. saved_f.close()
  7983. if silent is False:
  7984. if 'version' in saved_d:
  7985. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  7986. else:
  7987. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  7988. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  7989. tb_settings = QSettings("Open Source", "FlatCAM")
  7990. lock_state = self.ui.lock_action.isChecked()
  7991. tb_settings.setValue('toolbar_lock', lock_state)
  7992. # This will write the setting to the platform specific storage.
  7993. del tb_settings
  7994. # if quit:
  7995. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  7996. # t.start()
  7997. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  7998. def start_delayed_quit(self, delay, filename, should_quit=None):
  7999. """
  8000. :param delay: period of checking if project file size is more than zero; in seconds
  8001. :param filename: the name of the project file to be checked periodically for size more than zero
  8002. :param should_quit: if the task finished will be followed by an app quit; boolean
  8003. :return:
  8004. """
  8005. to_quit = should_quit
  8006. self.save_timer = QtCore.QTimer()
  8007. self.save_timer.setInterval(delay)
  8008. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  8009. self.save_timer.start()
  8010. def check_project_file_size(self, filename, should_quit=None):
  8011. """
  8012. :param filename: the name of the project file to be checked periodically for size more than zero
  8013. :param should_quit: will quit the app if True; boolean
  8014. :return:
  8015. """
  8016. try:
  8017. if os.stat(filename).st_size > 0:
  8018. self.save_in_progress = False
  8019. self.save_timer.stop()
  8020. if should_quit:
  8021. self.app_quit.emit()
  8022. except Exception:
  8023. traceback.print_exc()
  8024. def save_project_auto(self):
  8025. """
  8026. Called periodically to save the project.
  8027. 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
  8028. # progress.
  8029. :return:
  8030. """
  8031. if self.block_autosave is False and self.should_we_save is True and self.save_in_progress is False:
  8032. self.on_file_saveproject()
  8033. def save_project_auto_update(self):
  8034. """
  8035. Update the auto save time interval value.
  8036. :return:
  8037. """
  8038. log.debug("App.save_project_auto_update() --> updated the interval timeout.")
  8039. try:
  8040. if self.autosave_timer.isActive():
  8041. self.autosave_timer.stop()
  8042. except Exception:
  8043. pass
  8044. if self.defaults['global_autosave'] is True:
  8045. self.autosave_timer.setInterval(int(self.defaults['global_autosave_timeout']))
  8046. self.autosave_timer.start()
  8047. def on_options_app2project(self):
  8048. """
  8049. Callback for Options->Transfer Options->App=>Project. Copies options
  8050. from application defaults to project defaults.
  8051. :return: None
  8052. """
  8053. self.defaults.report_usage("on_options_app2project")
  8054. self.preferencesUiManager.defaults_read_form()
  8055. self.options.update(self.defaults)
  8056. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  8057. """
  8058. Shows a message on the FlatCAM Shell
  8059. :param msg: Message to display.
  8060. :param show: Opens the shell.
  8061. :param error: Shows the message as an error.
  8062. :param warning: Shows the message as an warning.
  8063. :param success: Shows the message as an success.
  8064. :param selected: Indicate that something was selected on canvas
  8065. :return: None
  8066. """
  8067. if show:
  8068. self.ui.shell_dock.show()
  8069. try:
  8070. if error:
  8071. self.shell.append_error(msg + "\n")
  8072. elif warning:
  8073. self.shell.append_warning(msg + "\n")
  8074. elif success:
  8075. self.shell.append_success(msg + "\n")
  8076. elif selected:
  8077. self.shell.append_selected(msg + "\n")
  8078. else:
  8079. self.shell.append_output(msg + "\n")
  8080. except AttributeError:
  8081. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  8082. class ArgsThread(QtCore.QObject):
  8083. open_signal = pyqtSignal(list)
  8084. start = pyqtSignal()
  8085. stop = pyqtSignal()
  8086. if sys.platform == 'win32':
  8087. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  8088. else:
  8089. address = ('/tmp/testipc', 'AF_UNIX')
  8090. def __init__(self):
  8091. super(ArgsThread, self).__init__()
  8092. self.listener = None
  8093. self.thread_exit = False
  8094. self.start.connect(self.run)
  8095. self.stop.connect(self.close_listener)
  8096. def my_loop(self, address):
  8097. try:
  8098. self.listener = Listener(*address)
  8099. while self.thread_exit is False:
  8100. conn = self.listener.accept()
  8101. self.serve(conn)
  8102. except socket.error:
  8103. try:
  8104. conn = Client(*address)
  8105. conn.send(sys.argv)
  8106. conn.send('close')
  8107. # close the current instance only if there are args
  8108. if len(sys.argv) > 1:
  8109. try:
  8110. self.listener.close()
  8111. except Exception:
  8112. pass
  8113. sys.exit()
  8114. except ConnectionRefusedError:
  8115. if sys.platform == 'win32':
  8116. pass
  8117. else:
  8118. os.system('rm /tmp/testipc')
  8119. self.listener = Listener(*address)
  8120. while True:
  8121. conn = self.listener.accept()
  8122. self.serve(conn)
  8123. def serve(self, conn):
  8124. while self.thread_exit is False:
  8125. msg = conn.recv()
  8126. if msg == 'close':
  8127. break
  8128. self.open_signal.emit(msg)
  8129. conn.close()
  8130. # the decorator is a must; without it this technique will not work unless the start signal is connected
  8131. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  8132. @pyqtSlot()
  8133. def run(self):
  8134. self.my_loop(self.address)
  8135. @pyqtSlot()
  8136. def close_listener(self):
  8137. self.thread_exit = True
  8138. self.listener.close()
  8139. # end of file